将一个32位的int值转换成一个浮点数 [英] Converting a 32-bit int value into a float

查看:930
本文介绍了将一个32位的int值转换成一个浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从文件中读取4个字节的程序。下面的十六进制应该是0.5浮点数:

  00 00 00 3F 

我目前有一个显示整数值的方法,并希望将整数从1056964608转换为0.5。这也应该能够处理负数浮点数。有人可以向我解释如何在Python 2.6中完成这项工作吗?使用 struct code> module:

 >>> struct.unpack(< f,\x00\x00\x00\x3f)
(0.5,)

如果你真的需要从整数转换,而不是从字节转换,你也可以这样做:

 >>> struct.unpack(< f,struct.pack(< I,1056964608))
(0.5,)


I have a program that reads from a file that grabs 4 bytes from that file. The below hex should be 0.5 in float:

00 00 00 3F

I currently have a method that displays integer values and would like to convert the integer from 1056964608 to 0.5. This should also be able to handle negative float numbers. Can someone explain to me how this can be done in Python 2.6?

解决方案

Using the struct module:

>>> struct.unpack("<f", "\x00\x00\x00\x3f")
(0.5,)

If you really need to convert from the integer, rather than just from the bytes, you can do that too:

>>> struct.unpack("<f", struct.pack("<I", 1056964608))
(0.5,)

这篇关于将一个32位的int值转换成一个浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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