The bin() method in Python is used to convert an integer to a binary string (a string consisting of only 0s and 1s). The resulting binary string is prefixed with "0b", indicating that it is a binary representation.
Example
x = 5
print(bin(x))
# Output: '0b101'
You can also use this method on a variable containing a number.
Example
x = 5
print(bin(x))
x = -5
print(bin(x))
"""
Output:
'0b101'
'-0b101'
"""
You can see that the negative number also include -0b prefix to indicate the number is negative. It is equivalent to format(x, 'b') You can also use format(x,'b') instead of bin(x)
Example
x = 5
print(format(x, 'b'))
# Output: '101'
It won't include '0b' prefix.
Younes Derfoufi
my-courses.net
my-courses.net
[…] Python bin(): This Python built-in function is used to convert an integer to a binary string. […]