How to Use the Python bin() Function
In this article, you will learn how to use the Python bin() function.
Python bin() Function
In Python, the bin() function is used to convert an integer number into its binary representation. The function takes a single argument, which should be an integer.
Here’s the syntax of the bin() function:
x: The integer number that you want to convert.
Here’s an example of how to use the bin() function:
<<< x = 5 <<< binary = bin(x) <<< print(binary) 0b101
In the above example, the bin() function is called with an integer x of value 5. The returned binary value is a string with a prefix of 0b. This prefix indicates that the value is in binary format. The actual binary value is 101.
If you want to remove the prefix 0b, you can simply slice the string from the second character using binary[2:]. Here’s an example:
<<< x = 5 <<< binary = bin(x)[2:] <<< print(binary) 101
This will print the binary value without the prefix 0b.
Note that bin() function works only with integers, and it raises a TypeError if you pass a non-integer value as an argument.