Managing ap_fixed in PYNQ

There is some good information in the other posts. Try check them again, including a response I’ll link below.
In your example, sinewave will be a list of floating point numbers. If you use fixed point in your FPGA design you need to convert from float to fixed.
If you have programmed in other languages you will have come across casting between types which is similar to what you need to do.

To go from float to fixed point is reasonably straight forward.
Fixed point numbers are like integers, but with a decimal point implied.

E.g.
0x0001 is integer 1
In fixed point, with 1 fractional bit the same value, 0x0001 is 0.5
With 2 fractional bits it is 0.25, and so on.
The number representation doesn’t change, but how the number is interpreted changes.

If you wanted to convert integers to fixed point you can just left shift the integer by the number of fractional bits.
E.g.
Integer 1 in fixed point with 1 fractional bit is 0x0010 (left shift 1 or multiply by 2^1)
With 2 fractional bits 1 is 0x0100 (left shift 2 or multiply by 2^2)

As integers are whole numbers, this would only allow you to generate whole fixed point numbers. i.e. All the fractional bits would be 0. This is why floats are usually used to generate the data initially, (as you want to do with your sinewave).

In this post, PeterOgden shows how to go from float to fixed:
How to use ap_fixed data type to communicate with the ip made by the vivado hls? - #5 by PeterOgden.

import numpy as np
fixed_ar = np.ndarray((1024,), 'i4')
float_ar = np.arange(-512, 512, dtype='f4')
fixed_ar[:] = float_ar * 256

Try test some numbers to make sure you understand what is happening.

This example uses 8 fractional bits. If you have for example 0.125 in floating point, multiply by 2^8 (256).
0.125 → 32.0 (float)
Converting to an integer gives 32, which is 0x20 in hex. If this is a fixed point with 8 fractional bits, it would be 0.125.

Converting from fixed to float is a little tricker, but suggested code has been posted by Peter in the link above.

Cathal

1 Like