简体   繁体   中英

Convert floating point to fixed point

I want to convert floating point sin values to fixed point values.

import numpy as np

Fs = 8000
f = 5
sample = 8000
x = np.arange(sample)
y = np.sin(2 * np.pi * f * x / Fs)

How can I easily convert this y floating point samples to fixed point samples?

Each element should be of 16bit and 1 bit integer part and 15 bits should be of fractional part, so that I can pass these samples to a DAC chip.

To convert the samples from float to Q1.15 , multiply the samples by 2 ** 15 . However, as mentioned in the comments, you can't represent 1.0 in Q1.15 , since the LSB is representing the sign. Therefore you should clamp your values in the range of [-1, MAX_Q1_15] where MAX_Q1_15 = 1.0 - (2 ** -15) . This can be done with a few helpful numpy functions.

y_clamped = np.clip(y, -1.0, float.fromhex("0x0.fffe"))
y_fixed = np.multiply(y_clamped, 32768).astype(np.int16)

Although you may fear this representation does not accurately represent the value of 1.0 , it is close enough to do computation with. For example, if you were to square 1.0 :

fmul_16x16 = lambda x, y: x * y >> 15
fmul_16x16(32767, 32767) # Result --> 32766

Which is very close, with 1-bit error.

Hopefully it helps.

You can use fxpmath to convert float values to fractional fixed-point. It supports Numpy arrays as inputs, so:

from fxpmath import Fxp

# your example code here

y_fxp = Fxp(y, signed=True, n_word=16, n_frac=15)

# plotting code here

eQ16.15

15 bits for fractional give you a very low value for amplitue resolution, so I plot Q5.4 to show the conversion in an exaggerated way:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM