首页 > 解决方案 > 循环一个字节数组以将 64 位转换为十进制

问题描述

我有一个非常大的文件,其中填充了 8 字节双精度数据。

我创建了这个循环来将所有数据转换为十进制,但我不断收到 TypeError: 'bytearray' object cannot be mapped as an integer

有小费吗?

import numpy as np
import matplotlib.pyplot as plt
import struct

#import file
f=open('nohead.stk','rb')

#Read in the data as a byte array (8-bit array)
ba = bytearray(f.read())
#number of bytes in the data file
length = len(ba)
print('N-bytes=',length)
#Since the data is in 64bits, convert eight bits at a time to a 64 bit
#Number of data points in file
nvals = int(length/8);
print('N-recordings for 64bits (8-byte data)=',nvals)

#loop over all values
for i in range(nvals):
    eightbytes[i] = ba[(i*8):(8+i*8)]
    unpacked[i] = struct.unpack('<d', eightbytes[i])[0]
    

f= open("Reading_Decimal.csv","w+")

f.write("%f\n" % (unpacked[i]))
f.close(); 

我在此处附加了前 24 个字节,因此您可以将其保存到文件中,看看是否可以让循环在前 3 个小数上工作

应该在-6左右

字节数组(b'\xef,\x81\xb6\\xf1\x17\xc0\xff\xe0\x9b\x80\xb6\xeb\x17\xc0\xbd\x98V\xb0\xbd\xa3\x17\xc0')

干杯

标签: arraysloopstype-conversionbyte

解决方案


自己得到了答案

希望这可以帮助其他人

import numpy as np
import matplotlib.pyplot as plt
import struct

#import file with no headers
f=open('15_stack_noheaders.stk','rb')

#Read in the data as a byte array (8-bit array)
ba = bytearray(f.read())
bs=str(ba)
#number of bytes in the data file
length = len(ba)
print('N-bytes=',length)
#Since the data is in 64bits, convert eight bits at a time to a 64 bit
#Number of data points in file
nvals = int(length/8);
print('N-recordings for 64bits (8-byte data)=',nvals)

#create empty array of zeros to fill
dat = np.zeros(nvals)

for i in range(0,nvals):
    dat[i] = struct.unpack('<d',ba[8*i:8+i*8])[0]

f= open("output.csv","w+")

for i in range(nvals) :
    f.write("%f\n" % (dat[i]))
f.close(); 

推荐阅读