Integer to Binary String in Python
We have an Integer and we need to convert the integer to binary string and print as a result. In this article, we will see how we can convert the integer into binary string using some generally used methods.
Example:
Input : 77
Output : 0b1001101
Explanation: Here, we have integer 77 which we converted into binary string
Using bin()
bin() function is the easiest way to convert an integer into a binary string. It returns the binary with a "0b" prefix to indicate it's a binary number.
n = 77
b = bin(n)
print(type(b),b)
Output
<class 'str'> 0b1001101
Using format()
format() function lets you convert a number to binary without the "0b" prefix. It gives you more control over formatting.
n = 81
b = format(n, 'b')
print(type(b),b)
Output
<class 'str'> 1010001
Using Bitwise operations
This method builds the binary string manually by dividing the number by 2 and collecting remainders. It's slower but helps you understand how binary conversion works.
n = 42
orig = n
b = ''
while n > 0:
b = str(n % 2) + b
n //= 2
b = b if b else '0'
print(type(b),b)
Output
<class 'str'> 101010
Explanation: We store the original number in orig, then use a loop to divide it by 2 and prepend each remainder (n % 2) to the string b. This builds the binary representation from right to left. If the number is 0, we set b to "0".
Related articles: