用Python浮动到二进制和二进制浮动 [英] Float to Binary and Binary to Float in Python

查看:132
本文介绍了用Python浮动到二进制和二进制浮动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我如何在python中将浮点数转换为32位二进制字符串以及如何从32位二进制字符串转换为浮点数吗?

Can anyone tell me how to convert a float number to 32-bit binary string and from a 32-bit binary string to a float number in python?

'bin'函数仅适用于整数.

'bin' function in python works only for integers.

我需要一个单一的字符串,如内部表示形式.我不希望在小数点之前和之后的数字之间用小数点后的数字分开的位字符串.

I need a single bit string as in internal representation. I do not want separate bit strings for the number before and after the decimal places joined by a decimal place in between.

标记的问题并未解释如何将二进制字符串转换为浮点型.

The question flagged does not explain how to convert binary string to float back.

推荐答案

此答案复制并根据来自马克·迪金森:

import struct

def float_to_bin(num):
    return format(struct.unpack('!I', struct.pack('!f', num))[0], '032b')

def bin_to_float(binary):
    return struct.unpack('!f',struct.pack('!I', int(binary, 2)))[0]

print float_to_bin(3.14)产生"01000000010010001111010110111000011".

print float_to_bin(3.14) yields "01000000010010001111010111000011".

print bin_to_float("11000000001011010111000010100100")产生"-2.71000003815".

print bin_to_float("11000000001011010111000010100100") yields "-2.71000003815".

这篇关于用Python浮动到二进制和二进制浮动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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