Python int to Binary | Integer to Binary Conversion

In the world of programming, the conversion of Python int to Binary is often necessary to better grasp the working and understanding of the computer. Before moving further, it is necessary to understand the basics. So, let us first perceive the meaning of these terms.

Int – It is the integer data type in python. It may be a positive or negative whole number without a decimal point. In python, the size of the int data type is unlimited.

Binary – It is a numeric system that comprises of solely two digits – 0 and 1.

In python there are several ways to convert an int to binary:

  • Traditional Method (Without Any Function)
  • Integer To Binary Using Bin() Function
  • Using Str.Format() Function
  • Integer To Binary Using F-Strings
  • Using Format()

Traditional method to Convert Python int to Binary (without any function):

Firstly, divide the number by 2 and add the remainder to a list. Then continue step 1 till the number is greater than 0. After this, reverse the list. At last, print the reversed list.

Source code to Convert Python int to Binary:

n=int (input ("Enter a number: "))
b= []
while(n>0):
    d=n%2
    b.append(d)
    n=n//2
b.reverse()
print("Binary Equivalent is: ")
for i in b:
    print(i,end="")

Output:

Traditional method to Convert Python int to Binary (without any function):

Explanation:

At first, the user will enter a number, which in this case is 11.
The while loop iterates till the number becomes greater than 0.

In each iteration, the digit is divided by 2, and the remainder is appended to the list. The list is then reversed (As done traditionally to convert an integer to binary theoretically) and printed. As a result, we get the binary equivalent of the integer.

Python int to Binary Using bin() function:

It is python’s built-in function. It takes integer as input and returns its binary representation in string format as output.

Syntax:

bin(num)

Parameters:

 num – integer

Note: if num is not an integer, __index()__ method should be implemented to return an integer. One may incur TypeError Exception

Example 1: Python int to Binary

num1 = 1
num2 = 7
print('The binary equivalent of 1 is:', bin(num1))
print('The binary equivalent of 7 is:', bin(num2))

Output:

Python int to Binary Using bin() function

Explanation:

Here the variable num1, num2 stores the integer value.

With the use of bin() function, a direct conversion of integer to binary occurs.

0b means that it is a binary string.

Example 2: Python int to Binary

class color:
    red = 1
    blue = 2
    green = 2

def __index__(self):
   return self.red + self.blue + self.green

print('The binary equivalent of color is:', bin(color()))

Output:

Example 2: Python Integer To Binary

Explanation:

 An object of class color is sent to the bin() method.

However, it doesn’t raise an error even though the object is not an integer.

This is because of the implementation of __index__() method which returns the sum of colors, which is an integer value. This sum is then passed to the bin() method.

Python int to Binary Using str.format() function:

It is a built-in function in python available for string formatting. To convert an integer to its binary equivalent, the string representation of type b can be used.

Syntax:

"{0:b}".format(num)

Parameters:

num -  integer 

Example:

num = 5
binary = "{0:b}".format(num)
print('Binary equivalent of num is',binary) 

Output:

Using str.format()

Explanation:

In this example, we have used the str.format() function for converting our integer to its binary equivalent (specified by using the type b). So, when the number 5 is passed as a parameter, the str.format() function converts it to its binary equivalent.

Python Int to binary using f-strings:

f-strings can be used in the version python 3.6 and above. In this, the string literal is prefixed with f or F.

Syntax:

f”{value}”

Parameter:

It converts the parameters enclosed in curly braces {} into string

Example:

num = 5
b = f'{num:b}'
print('Binary equivalent of 5 is',b)  

Output:

using f-strings:

Explanation:

fstring is an improved version for string formatting. When the value is passed, it is converted into binary (denoted by ‘b’), and this binary is then converted into string conveniently using the fstring.

Convert Python int to Binary Using format():

It is yet another inbuilt function available in python. It converts a specific value into a string as per the formatting specifications required by the user.

 Syntax:

format(value[num, format_spec])

Parameters:

num – integer

Example: Python int to Binary

num = 7
b = format(num, "b")
print('Binary of 7 is',b)

Output:

Convert Python int to Binary format():

Explanation:

Format () is a built-in function available in python. Here, we have used it to convert the integer value to its binary representation. As a result, when we pass the value 7, it converts it to binary as per our specified format.

Conclusion: Python int to Binary

These are various to convert Integer to Binary in Python. So, when one is doing a program, one should keep in mind the program’s needs and constraints and choose the best possible fit, as it may differ based on requirement and personal preference.

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

Happy Pythoning!

5 2 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments