ela*_*arr 3 python floating-point binary
我找到了几种将 Integer 和 Float 值转换为二进制的方法,它们各有各的问题。我需要在 0 和 10,000 的值之间输入一个整数/浮点数,转换为16 位(精确)二进制字符串,随机操作这些位,然后转换回整数/浮点数(取决于参数)。
但是,我一直在使用以下代码:
def convert_to_binary(value):
'''
Converts a float to a 16-bit binary string.
'''
[d] = struct.unpack('>Q', struct.pack('>d', value))
return str('{:016b}'.format(d))
def convert_back(bin_num):
'''
Converts binary string to a float.
'''
print type(bin_num)
print bin_num
bf = int_to_bytes(int(bin_num, 2), 8) # 8 bytes needed for IEEE 754 binary64.
print struct.unpack('>d', bf)[0]
return struct.unpack('>d', bf)[0]
# return struct.unpack('d', struct.pack('Q', bin_num))[0]
#bin_num.pack('B*').unpack('g').first
def int_to_bytes(n, minlen=0): # Helper function
'''
Turns integer/long to byte string.
'''
nbits = n.bit_length() + (1 if n < 0 else 0) # +1 for any sign bit.
nbytes = (nbits+7) // 8 # Number of whole bytes.
b = bytearray()
for _ in range(nbytes):
b.append(n & 0xff)
n >>= 8
if minlen and len(b) < minlen: # Zero padding needed?
b.extend([0] * (minlen-len(b)))
return bytearray(reversed(b)) # High bytes first.
Run Code Online (Sandbox Code Playgroud)
结果是这样的(以图片形式显示,因为我无法从我的终端复制和粘贴):
我知道有不同类型的二进制(有符号/无符号、不同的位数等),但我需要我的输出是我认为的无符号短......我的所有数字都是正值,并允许我稍后使用的位操作,它们需要正好是 16 位长-->(如果它们是浮点值,我可以使用二进制的额外数字,但只更改前 16 位,接下来的就是小数点,对吗?)
首先,我应该为 Float 输入和 Integer 输入编写函数吗?
其次,如何更改我的代码以允许所需的输出,而无需简单地使用pop等将二进制文件的长度减少到 16?
我遇到了同样的问题,所以我投票支持你的问题和答案,但我找到了一个更简单、更短的解决方案。
下面是一个例子:
In [1]: val = 15
In [2]: bin_ = '{0:016b}'.format(val)
In [3]: bin_
Out[3]: '0000000000001111'
Run Code Online (Sandbox Code Playgroud)
或者:
In [4]: bin_ = bin(val)[2:].zfill(16)
In [5]: bin_
Out[5]: '0000000000001111'
Run Code Online (Sandbox Code Playgroud)
In [6]: int(bin_, 2)
Out[6]: 15
Run Code Online (Sandbox Code Playgroud)