1

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?

MCharles
  • 289
  • 4
  • 11
  • `bin()` is not the right tool to convert to binary formatting with leading zeros (so a fixed number of bits). See the duplicate instead. `0b` is the Python literal notation for binary numbers, just like `0x` is used for hex numbers and `0o` for octal. See the [*Integer and long integer literals* documentation](https://docs.python.org/2/reference/lexical_analysis.html#integer-and-long-integer-literals). – Martijn Pieters Apr 26 '15 at 01:27
  • In other words, `bin()`, `hex()` and `oct()` produce output suitable for use as Python literal syntax for integer numbers in those bases; the documentation for each includes the phrase *The result is a valid Python expression*. – Martijn Pieters Apr 26 '15 at 01:27
  • Thank you for your response. I understand now why this is not the correct method for what I wish to do. – MCharles Apr 26 '15 at 01:43

2 Answers2

2

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.

user2357112
  • 260,549
  • 28
  • 431
  • 505
0

0b is the prefix for a binary number. It means that Python knows it's a number, and is just showing you it in binary.

Adam Smith
  • 52,157
  • 12
  • 73
  • 112
  • Is there any way to ensure that bin() does not leave out that first insignificant bit? My issue is that I need to grab the first 5, then the next 6, then the next 4 bits. and in the case of 0x3a81, its only returning 14 bits. – MCharles Apr 26 '15 at 01:32
  • 1
    @MCharles: see the duplicate I linked you to. `bin()` cannot do that because it was never the goal of that function to produce formatted binary output, only a string that could serve as a valid Python integer literal in binary notation. – Martijn Pieters Apr 26 '15 at 01:39