【问题标题】:pythonic way to get the binary32 representation of a number (int, float, or double)获取数字的二进制32表示的pythonic方法(int、float或double)
【发布时间】:2020-03-12 09:45:01
【问题描述】:

Python int to binary string?相关,我想知道一种pythonic方法来获取整数、浮点数或双精度数的IEEE-754 binary32表示。

例如 42.0 要转换为 1 10000100 01010 000000000000000000

【问题讨论】:

标签: python python-3.x floating-point ieee-754


【解决方案1】:

试试这个:

import struct

getBin = lambda x: x > 0 and str(bin(x))[2:] or "-" + str(bin(x))[3:]

def floatToBinary32(value):
    val = struct.unpack('I', struct.pack('f', value))[0]
    return getBin(val)

binstr = floatToBinary32(42.0)
print('Binary equivalent of 42.0:')
print(binstr + '\n')

【讨论】:

  • 谢谢。有没有内置的解决方案?将int转换为二进制很简单:format(42,"b"),有什么类似的吗?
猜你喜欢
  • 1970-01-01
  • 2021-07-15
  • 2011-05-28
  • 2018-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-14
相关资源
最近更新 更多