简体   繁体   中英

Convert 8 bits to byte array in python 2.7

I convert a long to a byte array and the I extract out 8 bits from each byte.

Here is the code snippet:-

import array
import struct
t = 1447460000
t = long(t)
store = struct.pack('!q', t)
byteArray = array.array('b', store)
print byteArray 

The output I get is:-

array('b', [0, 0, 0, 0, 86, 70, 124, -96])

Now code to get the bits:-

for bi in byteArray:
    actualValue = '{0:08b}'.format(bi)
    print actualValue 

The output I get is correct:-

00000000
00000000
00000000
00000000
01010110
01000110
01111100
-1000100

And now I change this output by replacing - in the last 8 bits by 1 and replace 0's buy 1's and other way round manually. So it becomes:-

11111111
11111111
11111111
11111111
10101001
10111001
10000011
10111011

So now my main question is to convert these bits again to a byte array. Thats it! Any help?Thanks!

If unsigned chars were used, you could simply use the XOR operator to convert your values. When applied with 0xFF , it will have the effect of inverting all of the bits.

import array
import struct
t = 1447460000
t = long(t)
store = struct.pack('!q', t)
byteArray = array.array('B', store)

print byteArray
print

for index, value in enumerate(byteArray):
    byteArray[index] = value ^ 0xFF         # XOR
    print '{:08b} -> {:08b}'.format(value, byteArray[index])

print
print byteArray

This would give you the following output:

array('B', [0, 0, 0, 0, 86, 70, 124, 160])

00000000 -> 11111111
00000000 -> 11111111
00000000 -> 11111111
00000000 -> 11111111
01010110 -> 10101001
01000110 -> 10111001
01111100 -> 10000011
10100000 -> 01011111

array('B', [255, 255, 255, 255, 169, 185, 131, 95])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM