Although you're only using 1
s and 0
s, this doesn't make the numbers you're typing in binary numbers: they're decimal (or octal if you start with 0
).
If you want to use binary numbers, prefix them with 0b
(assuming Python 2.6 at least). See this question.
You may also find bin()
useful if you want to print out the results.
EDIT: I get the following when trying 8bits:
>>> c = 00000001
>>> d = 10000000
>>> c | d
10000001
You're still confused about the 0b
notation. 10000000
isn't an 8-bit number, it's a decimal number, and you need at least 24 bits to represent it (bin(10000000)
is 0b100110001001011010000000
).
The reason 10000000 | 00000001
appears to "work" as if it was a binary representation is that 00000001
(which is an octal representation) also happens to be 1 in decimal. This really is 0b100110001001011010000000 | 0b000000000000000000000001
.
For example, 00000010
is 8
in decimal, so 10000000 | 00000010
would be 10000008
. If your number starts with 0
, it's an octal representation; if it starts with 0x
, it's hexadecimal; if it starts with 0b
, it's binary; otherwise, it's decimal.
There is a bit of luck with your particular use case (10000000 | 1
). Try 10000000 | 1000
, and your assumptions no longer work: that's 10000360
.
The operations you're using are bitwise, but the 1
s in the numbers you are providing do not represent individual bits.
What you'd probably want to see is:
>>> bin(0b10000000 | 0b00001000)
'0b10001000'
Here the number you're providing are in binary format (0b...
), the operation is bitwise (the operation was also bitwise for the other notations, it's just that the activated bits were not those you thought they were) and then you turn it back into a binary representation with bin(...)
.