浮点数转 16 位二进制补码,Python

Floating point to 16 bit Twos Complement Binary, Python

所以我认为以前有人问过这样的问题,但我在实现这个问题时遇到了很多麻烦。

我正在处理包含介于 -1 和 1 之间的浮点数的 CSV 文件。所有这些浮点数都必须转换为 16 位 2s 补码,不带前导“0b”。从那里,我将该数字转换为 2s 补码的字符串表示形式,CSV 中的所有内容将被写入一个 .dat 文件,中间没有 space。因此,例如,如果我读入 CSV 文件并且它有两个条目 [0.006534,-.1232],我会将每个条目转换为各自的 2s 补码并将它们一个接一个地写入 .dat 文件。

问题是我在如何将浮点数转换为 16 位 2s 补码的代码中卡住了。我一直在查看 等其他帖子,有人告诉我使用 .float() 函数,但我没有运气。

谁能帮我写一个脚本,接受一个浮点数,return它的 16 位 2s 补码字符串?它必须正好是 16 位,因为我正在处理 MIT 16 标准。

我正在使用 python 3.4 顺便说一句

回答标题中的问题:将[=​​40=]float转换为IEEE 754 half-precision binary floating-point format, you could use binary16

>>> from binary16 import binary16
>>> binary16(0.006534)
b'\xb0\x1e'
>>> binary16(-.1232)
b'\xe2\xaf'

numpy 产生类似的结果:

>>> import numpy as np
>>> np.array([0.006534, -.1232], np.float16).tostring()
b'\xb1\x1e\xe3\xaf'
>>> np.array([0.006534, -.1232], '>f2').tostring() # big-endian
b'\x1e\xb1\xaf\xe3'

My goal was to save the amplitudes as the ecg mit signal format 16
..snip..
the input is a .CSV file containing the f.p. values of the amplitude from a .WAV file (which is the recording of an ECG).

您可以直接读取 wav 文件并以 little-endian 字节顺序写入相应的 16 位二进制补码幅度,其中任何未使用的 high-order 位从最高位开始 sign-extended ('<h' 结构格式):

#!/usr/bin/env python3
import wave

with wave.open('ecg.wav') as wavfile, open('ecg.mit16', 'wb') as output_file:
    assert wavfile.getnchannels() == 1 # mono
    assert wavfile.getsampwidth() == 2 # 16bit
    output_file.writelines(iter(lambda: wavfile.readframes(4096), b''))

有时 bug in Python 3 .readframes() returns str 而不是 bytes。要解决此问题,请使用适用于空 strbytes:

if not data 测试
#!/usr/bin/env python3
import wave

with wave.open('ecg.wav') as wavfile, open('ecg.mit16', 'wb') as output_file:
    assert wavfile.getnchannels() == 1 # mono
    assert wavfile.getsampwidth() == 2 # 16bit
    while True:
        data = wavfile.readframes(4096)
        if not data:
            break
        output_file.write(data)