Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert bytes to bits in python

I am working with Python3.2. I need to take a hex stream as an input and parse it at bit-level. So I used

bytes.fromhex(input_str)

to convert the string to actual bytes. Now how do I convert these bytes to bits?

like image 975
user904832 Avatar asked Jan 11 '12 07:01

user904832


People also ask

How many bits is a byte Python?

Getting the size of an integer Note that 1 byte equals 8 bits. Therefore, you can think that Python uses 24 bytes as an overhead for storing an integer object. It returns 28 bytes. Since 24 bytes is an overhead, Python uses 4 bytes to represent the number 100.

How do you convert bytes to binary in Python?

Let us see how to write bytes to a file in Python. First, open a file in binary write mode and then specify the contents to write in the form of bytes. Next, use the write function to write the byte contents to a binary file.

How do you convert bits to bytes?

To convert from bits to bytes, simply divide the number of bits by 8. For example, 256 bits are equal to 256 / 8 = 32 bytes.

How do you convert bytes to numbers in Python?

To convert bytes to int in Python, use the int. from_bytes() method. A byte value can be interchanged to an int value using the int. from_bytes() function.


2 Answers

Another way to do this is by using the bitstring module:

>>> from bitstring import BitArray >>> input_str = '0xff' >>> c = BitArray(hex=input_str) >>> c.bin '0b11111111' 

And if you need to strip the leading 0b:

>>> c.bin[2:] '11111111' 

The bitstring module isn't a requirement, as jcollado's answer shows, but it has lots of performant methods for turning input into bits and manipulating them. You might find this handy (or not), for example:

>>> c.uint 255 >>> c.invert() >>> c.bin[2:] '00000000' 

etc.

like image 116
Alex Reynolds Avatar answered Sep 28 '22 04:09

Alex Reynolds


Operations are much faster when you work at the integer level. In particular, converting to a string as suggested here is really slow.

If you want bit 7 and 8 only, use e.g.

val = (byte >> 6) & 3 

(this is: shift the byte 6 bits to the right - dropping them. Then keep only the last two bits 3 is the number with the first two bits set...)

These can easily be translated into simple CPU operations that are super fast.

like image 41
Has QUIT--Anony-Mousse Avatar answered Sep 28 '22 03:09

Has QUIT--Anony-Mousse