[英]How to read double, float and int values from binary files in python?
我有一個用 C++ 創建的二進制文件。 第一個值是雙精度值,第二個值是整數值。 我正在使用 C++ 中的以下代碼讀取值。
double dob_value;
int integer_value;
fread(&dob_value, sizeof(dob_value), 1, fp);
fread(&integer_value, sizeof(integer_value), 1, fp);
我試圖在 python 中讀取同一個文件,但我遇到了問題。 我的 dob_value 是 400000000.00,我的 integer_value 是 400000。我在 python 中使用以下代碼進行 double。
def interpret_float(x):
return struct.unpack('d',x[4:]+x[:4])
with open(file_name, 'rb') as readfile:
dob = readfile.read(8)
dob_value = interpret_float(dob)[0]
val = readfile.read(4)
test2 = readfile.read(4)
integer_value = int.from_bytes(test2, "little")
我的 dob_value 是 400000000.02384186 。 我的問題是這個額外的小數來自哪里? 另外,如何獲得正確的 integer_value? 使用上面的代碼,我的 integer_value 是 1091122467。我也有整數后的浮點值,但我還沒有研究過。
如果鏈接斷開,以防萬一test.bin
包含
00 00 00 00 84 D7 B7 41 80 1A 06 00 70 85 69 C0。
您的二進制文件的前 8 個字節包含400000000.0 的正確41B7D78400000000十六進制表示。 跑步
import binascii
import struct
fname = r'test.bin'
with open(fname, 'rb') as readfile:
dob = readfile.read(8)
print(struct.unpack('d', dob)[0])
print(binascii.hexlify(dob))
產出
>> 400000000.0
>> b'0000000084d7b741'
這也是 double 的正確小端表示。
當你交換零件時,你會得到
print(binascii.hexlify(dob[4:]+dob[:4]))
>> b'84d7b74100000000'
如果您檢查十進制值,它將為您提供5.45e-315 ,而不是您所期望的。 而且,
struct.unpack('d', dob[4:]+dob[:4])[0]
>>5.44740625e-315
所以我不確定如何從上面的代碼中得到 400000000.02384186。 但是,要使用test.bin
獲得test.bin
,只需跳過開頭的四個字節:
with open(fname, 'rb') as readfile:
val = readfile.read(4)
dob = readfile.read(8)
dob = dob[4:]+dob[:4]
print(binascii.hexlify(dob))
print(struct.unpack('d', dob)[0])
>>b'801a060084d7b741'
>>400000000.02384186
二進制值0x41B7D78400061A80對應於400000000.02384186 。 因此,您首先讀取不正確的字節,然后錯誤地交換部分並獲得接近您期望的結果。 考慮到整數值,400000 是 0x00061A80,它也存在於二進制文件中,但你肯定讀過了那個字節,因為你將它們用於 double,所以你得到了錯誤的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.