How to concatenate bits in Python

I have two bytes, e.g. 01010101 and 11110000. I need to concatenate the four most significant bit of the second byte "1111" and the first whole byte, resulting something like 0000010101011111, namely, padding four zeros, the first whole byte and finally the four most significant bit of the second byte.

Any idea?

3

1 Answer

Try this:

first = 0b01010101 second = 0b11110000 res = (first<<4) | (second>>4) print bin(res) 

By shifting the first byte by 4 bits to the left (first<<4) you'll add 4 trailing zero bits. Second part (second>>4) will shift out to the right 4 LSB bits of your second byte to discard them, so only the 4 MSB bits will remain, then you can just bitwise OR both partial results (| in python) to combine them.

Splitting result back

To answer @JordanMackie 's question, you can split the res back to two variables, just you will loose original 4 least significant bits from second.

first = 0b01010101 second = 0b11110000 res = (first<<4) | (second>>4) print ("res : %16s" %(bin(res)) ) first2 = (res>>4) & 255 second2 = (res&0b1111)<<4 print ("first2 : %16s" % (bin(first2)) ) print ("second2: %16s" % (bin(second2)) ) 

Output looks like this:

res : 0b10101011111 first2 : 0b1010101 second2: 0b11110000 

First of the commands extracts original first byte. It shifts 4 LSB bits that came from second variable to the right (operator >>), so they will be thrown away. Next logical and operation & keeps only 8 lowest bits of the operation and any extra higher bits are thrown away:

first2 = (res>>4) & 255 

Second of the commands can restore only 4 MSB bits of the second variable. It selects only 4 LSB from the result that belong to second using logical multiplication (&). (anything & 1 = anything, anything & 0 = 0). Higher bits are discarded because they are AND'ed with 0 bit.

Next those 4 bits are shifted to the left. Zero bits appear at 4 lowest significant bit positions:

second2 = (res&0b1111)<<4 
2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like