在Python中处理字节和二进制数据

在Python中处理字节和二进制数据,python,binary,byte,Python,Binary,Byte,字节字符串中的四个连续字节一起指定某个值。然而,每个字节仅使用7位;最高有效位始终为零,因此其被忽略(总共为28位)。所以 将是000 0000000 0000000 0010000 0001 或者,为了清晰起见,10000 0001。这是四个字节代表的值。但我想要一个小数点,所以我这样做: >>> 0b100000001 257 我可以自己解决所有这些问题,但如何将其纳入程序?使用位移位和加法: bytes = b"\x00\x00\x02\x01" i = 0 for b

字节字符串中的四个连续字节一起指定某个值。然而,每个字节仅使用7位;最高有效位始终为零,因此其被忽略(总共为28位)。所以

将是
000 0000
000 0000
000 0010
000 0001

或者,为了清晰起见,
10000 0001
。这是四个字节代表的值。但我想要一个小数点,所以我这样做:

>>> 0b100000001
257

我可以自己解决所有这些问题,但如何将其纳入程序?

使用位移位和加法:

bytes = b"\x00\x00\x02\x01"
i = 0
for b in bytes:
    i <<= 7
    i += b     # Or use (b & 0x7f) if the last bit might not be zero.
print(i)
使用,您可以更快地完成大数字:

基准测试(2.4倍加速系数!):

quick.py(来自Mark Byers):

tst.py:

import os
import quick
import sevenbittoint

def tst(sz):
    bajts = os.urandom(sz)
  #for i in range(pow(2,16)):
  #  if i % pow(2,12) == 0: print(i)
  #  bajts = i.to_bytes(2, 'big')
    a = quick.quick(bajts)
    b = sevenbittoint.sevenbittoint(bajts)
    if a != b: raise Exception((i, bin(int.from_bytes(bajts,'big')), a, b))

第8位应该被忽略,所以应该是i+=(b&0x7f)@miara:谢谢,你说得对。我假设它是零,实际上它是零。你未经编辑的回答是对的。我将编辑我的问题。
257
janus@Zeus /tmp % python3 -m timeit -s "import tst" "tst.tst(10000)" 
10 loops, best of 3: 251 msec per loop
janus@Zeus /tmp % python3 -m timeit -s "import tst" "tst.tst(100)"  
1000 loops, best of 3: 700 usec per loop
janus@Zeus /tmp % python3 -m timeit -s "import sevenbittoint, os" "sevenbittoint.sevenbittoint(os.urandom(10000))"
10 loops, best of 3: 73.7 msec per loop
janus@Zeus /tmp % python3 -m timeit -s "import quick, os" "quick.quick(os.urandom(10000))"                        
10 loops, best of 3: 179 msec per loop
def quick(bites):
  i = 0
  for b in bites:
    i <<= 7
    i += (b & 0x7f)
    #i += b
  return i
import bitarray
import functools

def inttobitarray(x):
  a = bitarray.bitarray()
  a.frombytes(x.to_bytes(1,'big'))
  return a

def concatter(accumulator,thisitem):
  thisitem.pop(0)
  for i in thisitem.tolist():
    accumulator.append(i)
  return accumulator

def sevenbittoint(bajts):
  concatted = functools.reduce(concatter, map(inttobitarray, bajts), bitarray.bitarray())
  missingbits = 8 - len(concatted) % 8
  for i in range(missingbits): concatted.insert(0,0) # zeropad
  return int.from_bytes(concatted.tobytes(), byteorder='big')

def tst():
  num = 32768
  print(bin(num))
  print(sevenbittoint(num.to_bytes(2,'big')))

if __name__ == "__main__":
  tst()
import os
import quick
import sevenbittoint

def tst(sz):
    bajts = os.urandom(sz)
  #for i in range(pow(2,16)):
  #  if i % pow(2,12) == 0: print(i)
  #  bajts = i.to_bytes(2, 'big')
    a = quick.quick(bajts)
    b = sevenbittoint.sevenbittoint(bajts)
    if a != b: raise Exception((i, bin(int.from_bytes(bajts,'big')), a, b))