在python中把二进制数(由符号、万位数和指数组成)转换为十进制数。

问题描述 投票:0回答:1

我有一些32bits的二进制数字,我想把它们转换成十进制形式。我想把它们转换为十进制形式。是否存在任何内置的功能或一般的解决方案,为这个任务?

enter image description here.

python python-3.x python-2.7 numpy binary
1个回答
1
投票

你可以使用struct模块。

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

0
投票

工作从。

在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 是IEEE 754格式。

© www.soinside.com 2019 - 2024. All rights reserved.