python四字节十六进制float_如何转换4字节IEEE(little endian)浮点二进制表示

下面是一个如何用小尾数编码和解码的例子。这并没有解决任何舍入问题,但看起来这些问题是在上面的答案中解决的。import csv, os

import struct

test_floats = [1.2, 0.377, 4.001, 5, -3.4]

## write test floats to a new csv file:

path_test_csv = os.path.abspath('data-test/test.csv')

print path_test_csv

test_csv = open(path_test_csv, 'w')

wr = csv.writer(test_csv)

for x in test_floats:

wr.writerow([x])

test_csv.close()

## write test floats as binary

path_test_binary = os.path.abspath('data-test/test.binary')

test_binary = open(path_test_binary, 'w')

for x in test_floats:

binary_data = struct.pack('

test_binary.write(binary_data)

test_binary.close()

## read in test binary

binary = open(path_test_binary, 'rb')

binary.seek(0,2) ## seeks to the end of the file (needed for getting number of bytes)

num_bytes = binary.tell() ## how many bytes are in this file is stored as num_bytes

# print num_bytes

binary.seek(0) ## seeks back to beginning of file

i = 0 ## index of bytes we are on

while i < num_bytes:

binary_data = binary.read(4) ## reads in 4 bytes = 8 hex characters = 32-bits

i += 4 ## we seeked ahead 4 bytes by reading them, so now increment index i

unpacked = struct.unpack("

print tuple(unpacked)[0]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值