简体   繁体   English

将32位int值转换为float

[英]Converting a 32-bit int value into a float

I have a program that reads from a file that grabs 4 bytes from that file. 我有一个程序从一个文件中读取,该文件从该文件中获取4个字节。 The below hex should be 0.5 in float: 十六进制以下的浮点数应为0.5:

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. 我目前有一种显示整数值的方法,希望将整数从1056964608转换为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? 有人可以向我解释如何在Python 2.6中完成吗?

Using the struct module: 使用struct模块:

>>> 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,)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM