Search code examples
pythonpython-3.xbitwise-operators

Learning bitwise


I am having a hard time trying to figure out why I am getting the result with my code that I am getting.

c = int(format(ord('c'), 'b'))
h = int(format(ord('h'), 'b'))
result = c | h

print(c)
print(h)
print(result)

This returns a result of:

1100011

1101000

1101035

So my question is after the | operation, why is it 1101035 when (according to my understanding) it should be 1101011?


Solution

  • The call to format with the second argument being "b" gives you the binary representation of the number in the first argument. So, if you print it, you will see the "0"s and "1"s.

    However, when you use int on this result, withug informing int that your string is base 2, it thinks these are decimal numbers. So, it will "read" the sequence "1100011" (the binary representation of 99, the unicode codepoint for the "c" character), as "1_100_011", or "one million, one hundred thousand and eleven" - and that is the number in your c variable if you print or make any numeric operations with it.

    This can be easily solved by telling int that the numeric strings you are reading are binary themselves:

    c = int(format(ord('c'), 'b'), 2)
    

    (Passing 2 as the second argument to "int" to indicate the base). If you inspect "c" at this point, it contains the number 99, which will behave as expected with your "|" operator. Of course, if you are not looking at the binary representation of the number, there is no point in generating it to start with, so your code could be just c = ord('c')...