Python函数,将输入转换为64位,然后更改为8bytes输出

时间:2017-10-13 15:33:21

标签: python byte bit

我希望能够输入一系列数字,这些数字在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]

2 个答案:

答案 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)

一些注意事项:

  1. 你不得不将你的64位分成8段,这里是bytes变量。
  2. 在调用10时,如果不是2(在本例中为int),则需要传递基础。
  3. 我认为第8个元素应该是1而不是128