2017-10-13 32 views
0

我希望能够输入一系列的数字,在64位再现位,然后反向并显示8个字节。我一直在查找bitstring,但没有得到输出我期待的。Python函数,将输入到64位,然后更改为8bytes输出

代码

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

我想这可能就是你所要寻找的:

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) 

一些注意事项:

  1. 你无论如何都必须在64位打入8段,这里的bytes变量。
  2. 当您拨打int时,您需要通过基地的时间不是10(本例中为2)。
  3. 我觉得第8个元素应该是1而不是128
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 

比其他解决方案快运行时间

+0

不要发布链接的答案,以防链接过时。您应该在此总结其相关内容,以便您的答案是独立的,并提供学分或进一步阅读的链接。 – Reti43

相关问题