Floating point to 16 bit Twos Complement Binary, Python

2024/7/8 6:56:50

so I think questions like this have been asked before but I'm having quite a bit of trouble getting this implemented.

I'm dealing with CSV files that contain floating points between -1 and 1. All of these floating points have to be converted to 16 bit 2s complement without the leading '0b'. From there, I will convert that number to a string representation of the 2s complement, and all of those from the CSV will be written will be written to a .dat file with no space in between. So for example, if I read in the CSV file and it has two entries [0.006534, -.1232], I will convert each entry to their respective 2s complement and write them one after another onto a .dat file.

The problem is I'm getting stuck in my code on how to convert the floating point to a 16 bit 2s complement. I've been looking at other posts like this and I've been told to use the .float() function but I've had no luck.

Can someone help me write a script that will take in a floating point number, and return the 16 bit 2s complement string of it? It has to be exactly 16 bits because I'm dealing with the MIT 16 standard.

I am using python 3.4 btw

Answer

To answer the question in the title: to convert a Python float to 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 produces similar results:

>>> 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).

You could read the wav file directly and write the corresponding 16-bit two's complement amplitudes in little-endian byte order where any unused high-order bits are sign-extended from the most significant bit ('<h' struct format):

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

There is a bug in Python 3 that .readframes() returns str instead of bytes sometimes. To workaround it, use if not data test that works on both empty str and bytes:

#!/usr/bin/env python3
import wavewith wave.open('ecg.wav') as wavfile, open('ecg.mit16', 'wb') as output_file:assert wavfile.getnchannels() == 1 # monoassert wavfile.getsampwidth() == 2 # 16bitwhile True:data = wavfile.readframes(4096)if not data:breakoutput_file.write(data)
https://en.xdnf.cn/q/119710.html

Related Q&A

Flag the first non zero column value with 1 and rest 0 having multiple columns

Please assist with the belowimport pandas as pd df = pd.DataFrame({Grp: [1,1,1,1,2,2,2,2,3,3,3,4,4,4], Org1: [x,x,y,y,z,y,z,z,x,y,y,z,x,x], Org2: [a,a,b,b,c,b,c,c,a,b,b,c,a,a], Value: [0,0,3,1,0,1,0,5,…

How to split up data from a column in a csv file into two separate output csv files?

I have a .csv file, e.g.:ID NAME CATEGORIES 1, x, AB 2, xx, AA 3, xxx, BAHow would I get this to form two output .csv files based on the category e.g.:File 1:ID NAME CATEGORY 1, x, A 2, xx, A 3, …

Discord.py spellcheck commands

Recently, I looked up Stack Overflow and found this code which can check for potential typos: from difflib import SequenceMatcher SequenceMatcher(None, "help", "hepl").ratio() # Ret…

Django Model Form doesnt seem to validate the BooleanField

In my model the validation is not validating for the boolean field, only one time product_field need to be checked , if two time checked raise validation error.product_field = models.BooleanField(defau…

For loop only shows the first object

I have a code that loops through a list of mails, but it is only showing the first result, even though there are also other matches. The other results require me to loop over the mails again only to re…

IndexError: pop from empty list

I need help. I have no idea why I am getting this error. The error is in fname = 1st.pop()for i in range(num) :fname = lst.pop()lTransfer = [(os.path.join(src, fname), os.path.join(dst, fna…

Cannot import name StandardScalar from sklearn.preprocessing [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar q…

unable to solve strptime() issue even after trying all the formats

Im using the following code:data[Input_volTargetStart][1]>time.strptime(data[Dates][1], "%d %b $y")When I try to run it, I get this error:ValueError: time data 04-Jun-99 does not match for…

OSError. locateOnScreen not working in pyautogui

import pyautoguipyautogui.locateOnScreen(photo.png)Error: OSError: Failed to read photo.png because file is missing, has improper permissions, or is an unsupported or invalid format

Insert into table using For In Range and keys of the value

I have a query (sql1) that populates data, and I am trying to insert the outcome of this data (sql1) as well as other inputs into same table.Here is first query (sql1).sql1 = Select Creator_Id, Record…