Python Forum

Full Version: Help Understanding Some Code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm trying to understand this code:
def readSize(self):
        b1 = ord(self.read(1))
        if b1 & 0b10000000:  # 1 byte
            return b1 & 0b01111111
        elif b1 & 0b01000000:  # 2 bytes
            return unpack(">H", bchr(b1 & 0b00111111) + self.read(1))[0]
        elif b1 & 0b00100000:  # 3 bytes
            return unpack(">L", b"\0" + bchr(b1 & 0b00011111) + self.read(2))[0]
        elif b1 & 0b00010000:  # 4 bytes
            return unpack(">L", bchr(b1 & 0b00001111) + self.read(3))[0]
        elif b1 & 0x00001000:  # 5 bytes
            return unpack(">Q", b"\0\0\0" + bchr(b1 & 0b00000111) + self.read(4))[0]
        elif b1 & 0b00000100:  # 6 bytes
            return unpack(">Q", b"\0\0" + bchr(b1 & 0b0000011) + self.read(5))[0]
        elif b1 & 0b00000010:  # 7 bytes
            return unpack(">Q", b"\0" + bchr(b1 & 0b00000001) + self.read(6))[0]
        elif b1 & 0b00000001:  # 8 bytes
            return unpack(">Q", b"\0" + self.read(7))[0]
        else:
            assert b1 == 0
raise EbmlException("undefined element size")
I've a basic knowledge of bitwise operators via Google. I will get into more depth later. I just don't understand what this code is doing. What is
0b1000000
I know it's a binary number, but what does the "0b" represent? I've seen "0x" prefacing binary numbers (though I don't really get what it means either), but never "0b".
I would appreciate any help decoding this for me.

Thanks,
malonn
0b indicates that the number is in a binary representation and 0x in a hexadecimal representation.

>>> 0b011
3
>>> 0x011
17
>>> 
011 in binary is: 2²*0 + 2¹*1 + 2⁰ * 1 = 3 (decimal)
011 in hexa is: 16²*0 + 16¹*1 + 16⁰ * 1 = 17 (decimal)
Ah, gotcha. Thank you @gontajones. I have read about converting base-2 and base-16 numbers to base-10, and it is essential in working with bytes and byte objects in Python. Good stuff.

That's a positive step in understanding the above code.