Search code examples
pythonbinaryslicebin

What does the b mean in the return of python bin()?


I am trying to convert hex to binary in python. I am using:

hexNumber = "0x3a81"
print bin(int(hexNumber,16))

The return I am getting for hexNumber = 0x3a81 is: 0b11101010000001 I believe the correct conversion is 0011101010000001

The return I am getting for hexNumber = 0x53f6 is: 0b101001111110110 I believe the correct conversion is 0101001111110110

What does the b mean? If I am trying to slice the first 5 bits of the binary number, do I ignore the b or count it towards the string length?


Solution

  • The 0b is like the 0x on your hexNumber; it's an indication that the number is in a certain base, specifically base 2. If you want the binary digits, just slice that part off.