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

时间:2015-07-16 20:34:14

标签: python python-3.x floating-point twos-complement

所以我认为之前已经提出了这样的问题,但是我实现这个问题时遇到了很多麻烦。

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

问题是我的代码中遇到了如何将浮点数转换为16位2s补码的问题。我一直在寻找其他帖子,如this,我被告知使用.float()函数,但我没有运气。

有人可以帮我写一个脚本,它会接收一个浮点数,并返回它的16位2s补码字符串吗?它必须是16位,因为我正在处理MIT 16标准。

我正在使用python 3.4 btw

1 个答案:

答案 0 :(得分:0)

要回答标题中的问题:要将Python float转换为IEEE 754 half-precision binary floating-point format,您可以使用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'
  

我的目标是将振幅保存为心电图信号格式16
  ..snip ..
   输入是一个包含f.p.的.CSV文件。来自.WAV文件的幅度值(即ECG的记录)。

您可以直接读取wav文件,并以little-endian字节顺序写入相应的16位二进制补码幅度,其中任何未使用的高位都从最高有效位({{1)进行符号扩展结构格式):

'<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'')) .readframes()有时会str返回bytes而不是if not data。要解决此问题,请使用适用于空strbytes的{​​{1}}测试:

#!/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)
相关问题