Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Python How can I read the bits in a byte?

Tags:

python

byte

bits

People also ask

How do you extract bits from a byte in Python?

Algorithm. Extractionbit(no,k,pos) /*user input number is stored in variable no, extracted bit is stored in variable k and the position of bit is pos. */ Step 1 : first convert the number into its binary form using bin(). Step 2 : remove the first two character.

How do you read bits in a byte?

You can mask out the bits you want from a byte using bitwise AND. In general, to test for individual bits, C has bitwise operators. Example: SO: C/C++ check if one bit is set in, i.e. int variable.

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.


Read the bits from a file, low bits first.

def bits(f):
    bytes = (ord(b) for b in f.read())
    for b in bytes:
        for i in xrange(8):
            yield (b >> i) & 1

for b in bits(open('binary-file.bin', 'r')):
    print b

The smallest unit you'll be able to work with is a byte. To work at the bit level you need to use bitwise operators.

x = 3
#Check if the 1st bit is set:
x&1 != 0
#Returns True

#Check if the 2nd bit is set:
x&2 != 0
#Returns True

#Check if the 3rd bit is set:
x&4 != 0
#Returns False

With numpy it is easy like this:

Bytes = numpy.fromfile(filename, dtype = "uint8")
Bits = numpy.unpackbits(Bytes)

More info here:
http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromfile.html


You won't be able to read each bit one by one - you have to read it byte by byte. You can easily extract the bits out, though:

f = open("myfile", 'rb')
# read one byte
byte = f.read(1)
# convert the byte to an integer representation
byte = ord(byte)
# now convert to string of 1s and 0s
byte = bin(byte)[2:].rjust(8, '0')
# now byte contains a string with 0s and 1s
for bit in byte:
    print bit

Joining some of the previous answers I would use:

[int(i) for i in "{0:08b}".format(byte)]

For each byte read from the file. The results for an 0x88 byte example is:

>>> [int(i) for i in "{0:08b}".format(0x88)]
[1, 0, 0, 0, 1, 0, 0, 0]

You can assign it to a variable and work as per your initial request. The "{0.08}" is to guarantee the full byte length


To read a byte from a file: bytestring = open(filename, 'rb').read(1). Note: the file is opened in the binary mode.

To get bits, convert the bytestring into an integer: byte = bytestring[0] (Python 3) or byte = ord(bytestring[0]) (Python 2) and extract the desired bit: (byte >> i) & 1:

>>> for i in range(8): (b'a'[0] >> i) & 1
... 
1
0
0
0
0
1
1
0
>>> bin(b'a'[0])
'0b1100001'