Both x
and y
hold integer values, you just choose to use 0b
binary literals to define them.
If you want to combine the two into z
, you can easily do so using a shifting operation and binary bitwise operations:
>>> x = 0b00010101010
>>> y = 0b1110000
>>> z = (x << 7) | y
>>> bin(z)
'0b101010101110000'
Do note that python does not track how many bits 'precision' you want to keep on such values; you defined y
with 7 bits of information, so I had to shift x
to the left 7 times to make room for y
. You'd have to track this information yourself.
Your next problem is representing data as base64 as this format requires you to provide it with bytes only. That's chunks of 8 bits of binary data. This means you'll have to align your bits to the 8-bit boundaries and then turn these into bytes (e.g. strings). You won't be able to get around that, I'm afraid.
I'd use the struct
module for that, it lets you pack integers and other data-types into bytes with ease:
>>> import struct
>>> struct.pack('>H', x)
'\x00\xaa'
>>> struct.pack('>H', x).encode('base64')
'AKo=\n'
In the above example I've packed the 11-bits x
variable as an unsigned short (using the little-endian standard C format), resulting in 2 bytes of information, then encoded that to base64.
The reverse then requires decoding from base64, then an unpack operation:
>>> foo = struct.unpack('>H', 'AKo=\n'.decode('base64'))[0]
>>> bin(foo)
'0b10101010'
Again, Python doesn't track how many bits of information is important to you, you'll have to track that explicitly.