Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
community creator

How to add binary numbers in Python

Sonith Bingi

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 inputin integer form using 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.

Example:

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.

Example:

int(‘1234’) would return 1234 and int(43.752) would only return the integer part before the decimal point, i.e., 43.

Code

b1='100010' #Decimal value: 34
b2='101001' #Decimal value: 41

res = bin(int(b1,2) + int(b2,2)) #Passing the base value of 2 for binary to the int() function
print(res)

#If the user wants to get rid of the suffix '0b' at the start
print(res[2:])

RELATED TAGS

python
community creator
RELATED COURSES

View all Courses

Keep Exploring