Floating point to 16 bit Twos Complement Binary, Python -


so think questions have been asked before i'm having quite bit of trouble getting implemented.

i'm dealing csv files contain floating points between -1 , 1. of these floating points have converted 16 bit 2s complement without leading '0b'. there, convert number string representation of 2s complement, , of csv written written .dat file no space in between. example, if read in csv file , has 2 entries [0.006534, -.1232], convert each entry respective 2s complement , write them 1 after onto .dat file.

the problem i'm getting stuck in code on how convert floating point 16 bit 2s complement. i've been looking @ other posts this , i've been told use .float() function i've had no luck.

can me write script take in floating point number, , return 16 bit 2s complement string of it? has 16 bits because i'm dealing mit 16 standard.

i using python 3.4 btw

to answer question in title: convert python float ieee 754 half-precision binary floating-point format, use binary16:

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

numpy produces similar results:

>>> import numpy 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 save amplitudes ecg mit signal format 16
..snip..
input .csv file containing f.p. values of amplitude .wav file (which recording of ecg).

you read wav file directly , write corresponding 16-bit two's complement amplitudes in little-endian byte order unused high-order bits sign-extended significant bit ('<h' struct format):

#!/usr/bin/env python3 import wave  wave.open('ecg.wav') wavfile, open('ecg.mit16', 'wb') output_file:     assert wavfile.getnchannels() == 1 # mono     assert wavfile.getsampwidth() == 2 # 16bit     output_file.writelines(iter(lambda: wavfile.readframes(4096), b'')) 

there bug in python 3 .readframes() returns str instead of bytes sometimes. workaround it, use if not data test works on both empty str , bytes:

#!/usr/bin/env python3 import wave  wave.open('ecg.wav') wavfile, open('ecg.mit16', 'wb') 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) 

Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -