Binary numbers are the core of the electrical components inside a computer. These numbers are used to simplify the design of computers and technologies related to them. Python has a vast library of built-in functions.
We can look at the addition of binary numbers in Python to understand how the addition of binary numbers occurs inside a computer from the user-given bin()
and int()
functions.
bin()
bin() is a built-in Python function that converts a given integer to its corresponding binary format. The output of this is a string that has a prefix (0b) added to the converted result to indicate that it is a binary format.
bin(5) returns 0b101. Here, 101 is the binary form of 5 and 0b is the added suffix.
int()
Integers in Python are represented by the int class. It can be used to store positive and negative integers, but it cannot hold fractions.
The int()
function converts a variable of any data type to its corresponding value in int data type.
int(‘1234’) would return 1234 and int(43.752) would only return the integer part before the decimal point, i.e., 43.
b1='100010' #Decimal value: 34b2='101001' #Decimal value: 41res = bin(int(b1,2) + int(b2,2)) #Passing the base value of 2 for binary to the int() functionprint(res)#If the user wants to get rid of the suffix '0b' at the startprint(res[2:])