francof2a / fxpmath

A python library for fractional fixed-point (base 2) arithmetic and binary manipulation with Numpy compatibility.
MIT License
183 stars 21 forks source link

Reinterpret fixed-point number #29

Closed udara28 closed 3 years ago

udara28 commented 3 years ago

Is there a way I can reinterpret a fixed point number with different number of fractional bits?

In my use case I'm receiving MyHDL intbv objects which are actually fixed-point values with some fractional bits. If I create a Fxp object like Fxp(int(x), True, 5, 2) then it will modify the bit pattern. For example say I have 2 fractional bits. if x=0b00010 then x actually represent 0.5. But if I do Fxp(int(x), True, 5, 2) it will become x=0b01000. Is there a way I can keep x as 0b0010 and just change the number of fractional bits so that it can be interpreted as 0.5 or 2?

francof2a commented 3 years ago

Hello @udara28

I think you need to load a raw value in Fxp, or I misunderstood your problem.

If I was right, you can do that as following:

x_fxp = Fxp(int(x), True, 5, 2, raw=True)

or you can assign new raw value after creation:

# x_fxp = Fxp(...)
# ...
x_fxp.set_val(int(x), raw=True)

Please, tell me if it solved in this way

udara28 commented 3 years ago

@francof2a thanks for your reply. I think the first method can't work since raw is not a parameter in the Fxp init function. The second method did the trick for me. I didn't notice any mention about the raw parameter in the README. So it would be really helpful if it can be added there. Thanks again for the help and I'm closing this issue.

francof2a commented 3 years ago

The first method is going to work because raw is passed as kwarg to the init function.

You're right about documentation. It is not updated. I hope update soon. Thank you!