将python float转换为字节 [英] Converting python float to bytes

查看:170
本文介绍了将python float转换为字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将Python浮点数转换为字节数组,将其编码为32位小尾数IEEE浮点数,以便将其写入二进制文件.

I want to convert a Python float into a byte array, encoding it as a 32 bit little-endian IEEE floating point number, in order to write it to a binary file.

在Python 3中执行此操作的现代Pythonic方法是什么?对于整数,我可以执行 my_int.to_bytes(4,'little'),但是没有用于浮点数的 to_bytes 方法.

What is the modern Pythonic way to do that in Python 3? For ints I can do my_int.to_bytes(4,'little'), but there is no to_bytes method for floats.

如果我可以一次为numpy数组中的每个浮点数(使用dtype numpy.float32)做到这一点,那就更好了.但是请注意,我需要将其作为字节数组获取,而不仅仅是立即将数组写入文件中.

It's even better if I can do this in one shot for every float in a numpy array (with dtype numpy.float32). But note that I need to get it as a byte array, not just write the array to a file immediately.

有一些听起来相似的问题,但它们似乎主要是关于获取十六进制数字,而不是写入二进制文件.

There are some similar-sounding questions, but they seem mostly to be about getting the hex digits, not writing to a binary file.

推荐答案

使用正确的 dtype ,您可以将数组的数据缓冲区写入字节串或二进制文件:

With the right dtype you can write the array's data buffer to a bytestring or to a binary file:

In [449]: x = np.arange(4., dtype='<f4')                                        
In [450]: x                                                                     
Out[450]: array([0., 1., 2., 3.], dtype=float32)
In [451]: txt = x.tostring()                                                    
In [452]: txt                                                                   
Out[452]: b'\x00\x00\x00\x00\x00\x00\x80?\x00\x00\x00@\x00\x00@@'
In [453]: x.tofile('test')                                                                                                                           
In [455]: np.fromfile('test','<f4')                                             
Out[455]: array([0., 1., 2., 3.], dtype=float32)
In [459]: with open('test','br') as f: print(f.read())                          
b'\x00\x00\x00\x00\x00\x00\x80?\x00\x00\x00@\x00\x00@@'

更改结尾:

In [460]: x.astype('>f4').tostring()                                            
Out[460]: b'\x00\x00\x00\x00?\x80\x00\x00@\x00\x00\x00@@\x00\x00'

这篇关于将python float转换为字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆