![]() |
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 Integer to Binary String in PythonBelow are some of the ways to convert Integer to Binary String in Python:
Integer to Binary String Using bin() functionIn 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() FunctionIn 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 OperatorIn 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'> Integer to Binary String in Python – FAQsHow to convert Integer to Binary String in Python
What built-in functions assist in binary conversion in Python?
How to format binary strings for readability in Python?
What are common applications of binary conversion in Python?
How to handle large integers during binary conversion in Python?
|
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |