Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: convert a byte to binary and shift its bits?

Tags:

python

binary

I want to convert an encoding to another encoding in Python for a school project. However, the encoding I am translating from will add a padding to its encoding on the first bit.

How do I shift an binary number sequence to the left by one, so that it goes from:

00000001 11001100 01010101 and so on

to

00000011 10011000 10101010 and so on

so the end result's lowest bit will be the former's highest bit number?

like image 753
needoriginalname Avatar asked Oct 19 '25 14:10

needoriginalname


2 Answers

You can use the << operator to left shift, and conversely >> will right shift

>>> x = 7485254
>>> bin(x)
'0b11100100011011101000110'
>>> bin(x << 1)
'0b111001000110111010001100'
like image 69
Cory Kramer Avatar answered Oct 21 '25 03:10

Cory Kramer


You could use the bitstring library which allows for bitwise operations on arbitrarily long bitstrings e.g. to import and shift your binary number:

>>> import bitstring
>>> bitstring.BitArray(bin='0b11100100011011101000110') << 1
BitArray('0b11001000110111010001100')
like image 34
Pierz Avatar answered Oct 21 '25 04:10

Pierz