Arrays 如何将字节转换回整数列表,当使用2字节/int和';大';点菜?
我正在使用to_bytes函数将整数列表转换为字节。因为我列表中的一些数字大于255,并且可能变得相当大;我任意决定使用3个字节来存储它们。 因此,在我的循环中,我执行以下操作:-Arrays 如何将字节转换回整数列表,当使用2字节/int和';大';点菜?,arrays,python-3.x,list,file-io,byte,Arrays,Python 3.x,List,File Io,Byte,我正在使用to_bytes函数将整数列表转换为字节。因为我列表中的一些数字大于255,并且可能变得相当大;我任意决定使用3个字节来存储它们。 因此,在我的循环中,我执行以下操作:- for number in original_array: byte_file_writer_delta.write(number.to_bytes(3, byteorder='big')) 例如,如果我的原始数组中有一个像[1900,1901]这样的数字。当我使用下面的代码将其转换回来时,我得到如下结果
for number in original_array:
byte_file_writer_delta.write(number.to_bytes(3, byteorder='big'))
例如,如果我的原始数组中有一个像[1900,1901]这样的数字。当我使用下面的代码将其转换回来时,我得到如下结果
[0,7108,0,7109]在我的输出中当我从文件中读回数字1900和1901时,我试图查看它们。我用来读回数字的代码是:
byte_file_reader= open('byte_file_inverted_index.txt', 'rb')
byte_file_reader.seek(byte_offset)
mybytes=byte_file_reader.read(byte_size)
print(list(mybytes))
看看下面的脚本是否对您有所帮助。。。我相信bytes_to_int函数会对您很好 我使用了一些数字进行测试(原始的_数组)
你的
字节偏移量是多少?你怎么计算呢?它与从原始数组写入的字节位置有何关联?谢谢!您的代码很有用,但这是我的问题,在将原始_数组作为字节转储到文件中后,我无法访问它。所以基本上我必须从文件中获取列表并解码。因此,我不能真正使用dec=bytes_to_int(enc)行,因为我在读回文件后无法访问各个enc(数字)。这只是一个字节块,我需要从中提取单个数字。其余的我都算出来了!谢谢!:)byte\u file\u reader=open('byte\u file\u inversed\u index.txt','rb')byte\u file\u reader.seek(byte\u offset)mybytes=byte\u file\u reader.read(byte\u size)array1=[]而len(mybytes)>0:character=mybytes[:3]array1.append(bytes\u to\u-int(character))mybytes=mybytes[3:]返回array1
我正在迭代中使用你的函数。我认为这是正确的
original_array = [1,2,3,4,5,6,7,10,1500,2999,50000,789456,9999999]
def bytes_to_int(bytes):
result = 0
for b in bytes:
result = result * 256 + int(b)
return result
for number in original_array:
enc = number.to_bytes(3, byteorder='big')
print(enc)
dec = bytes_to_int(enc)
print(dec)