简体   繁体   English

将二进制数(由符号、尾数和指数组成)转换为 python 中的十进制数

[英]convert a binary number (consists of the sign, mantissa and exponent ) to decimal number in python

I have some 32bits binary numbers.我有一些 32 位二进制数。 I want to convert them to decimal form.我想将它们转换为十进制形式。 does exist any built-in function or general solution for this task?是否存在任何内置 function 或此任务的通用解决方案? The following image shows an example.下图显示了一个示例。

在此处输入图像描述 . .

You can use struct module.您可以使用结构模块。

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

print(bin_to_float("11000011011110001100000000000000"))
##Output -248.75

Working from:工作地点:

What's the correct way to convert bytes to a hex string in Python 3? 在 Python 3 中将字节转换为十六进制字符串的正确方法是什么?

In [54]: bytes.fromhex('c378c000')                                                                     
Out[54]: b'\xc3x\xc0\x00'
In [55]: np.frombuffer(bytes.fromhex('c378c000'), '>f4')                                               
Out[55]: array([-248.75], dtype=float32)

np.float32 is IEEE 754 format. np.float32是 IEEE 754 格式。

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

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