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
Integer to Binary String in Python
Below are some of the ways to convert Integer to Binary String in Python:
- Using bin() Function,
- Using format() Function,
- Using bitwise Operator
Integer to Binary String Using bin() function
In this example, The variable `ans` holds the binary string representation of the integer `num` using the `bin()` function, and the result is printed, displaying "The binary string is" followed by the binary string.
Python3
num = 77
ans = bin(num)
# The binary string 'ans' is printed
print(type(num))
print("The binary string is", ans)
print(type(ans))
Output
<class 'int'> The binary string is 0b1001101 <class 'str'>
Integer to Binary String Using format() Function
In this example, The variable `ans` stores the binary string representation of the integer `num` using the `format()` method with the 'b' format specifier, and it is then printed with the message "The binary string is".
Python3
num = 81
ans = format(num, 'b')
print(type(num))
print("The binary string is", ans)
print(type(ans))
Output
<class 'int'> The binary string is 1010001 <class 'str'>
Integer to Binary String Using bitwise Operator
In this example, below code , a binary string is manually constructed by iteratively taking the remainder of the number divided by 2 and appending it to the left of the `binary_string`. The process continues until the number becomes zero. The resulting binary representation is then printed using an f-string.
Python3
# Manual conversion with bitwise operations
binary_string = ''
number = 42
while number > 0:
binary_string = str(number % 2) + binary_string
number //= 2
# Handle the case when num is 0
binary_result = binary_string if binary_string else '0'
# Example usage
print(type(number))
print(f"The binary representation of {number} is: {binary_result}")
print(type(binary_result))
Output
<class 'int'> The binary representation of 0 is: 101010 <class 'str'>