简体   繁体   English

在python 2.7中将8位转换为字节数组

[英]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. 我将long转换为字节数组,然后从每个字节中提取8位。

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. 现在,我通过以下方式更改此输出:将最后8位替换为1,然后手动替换0的买入1和其他方式。 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. 如果使用了无符号字符,则只需使用XOR运算符即可转换您的值。 When applied with 0xFF , it will have the effect of inverting all of the bits. 当应用0xFF ,它将具有反转所有位的效果。

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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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