我希望能够输入一系列数字,这些数字在64位中呈现一位...然后反转它并显示8个字节。我一直看着bitstring,但还没有得到我期待的东西。
def Pconvert(*varloadID):
bits = [0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,]
for x in varloadID:
x -= 1
bits[x] = 1
print bits
j = int(''.join(map(str, bits)))
print j
Pconvert(1,8,64)
[129,0,0,0,0,0,0,128]
答案 0 :(得分:0)
import struct
def Pconvert(*varloadID):
bits = [0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, ]
for x in varloadID:
x -= 1
bits[x] = 1
j = int(''.join(map(str, bits)), 2)
print(j)
bytestr = struct.pack('>Q', j).decode('cp1252')
a = list()
for i in bytestr:
a.append(ord(i))
print(a.__len__())
return a
使用struct比其他解决方案具有更快的运行时间
答案 1 :(得分:0)
我认为这可以做你正在寻找的事情:
def Pconvert(*varloadID):
bits = [0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,]
for x in varloadID:
bits[x-1] = 1
print bits
bytes = [bits[i*8:i*8+8] for i in xrange(0,8)]
return map(lambda byte: int(''.join(map(str,byte)),2),bytes)
print Pconvert(1,8,64)
一些注意事项:
bytes
变量。10
时,如果不是2
(在本例中为int
),则需要传递基础。1
而不是128
。