Peterstone
Peterstone

Reputation: 7449

VHDL: How to convert a floating point number to integer

I want to pass a from a floating point number to a integer number. Basically I have a floating point number between 1 and 0, with three decimal places and I want to pass it to a integer number as if I multiply it by 1000. I suspect there should be a more optimal way to do it than using the arithmetic mult operation x1000. I´m looking for a piece of code preferably. Thank you to all possible pices of code, references, articles or comments.

Upvotes: 1

Views: 16311

Answers (2)

Philippe
Philippe

Reputation: 3730

If you want this for simulations only you can do something like:

i <= integer(r * 1000);

If you want to synthesize to hardware, you might consider a power-of two to make the logic more compact.

i <= integer(r * 1024);

However, @Potatoswatter has a valid point: you should consider if you really need a real (floating point).

Upvotes: 3

Potatoswatter
Potatoswatter

Reputation: 137810

If you have a binary floating point number which is not a constant, there is no way to convert it to an integer in [0,1000] without actually performing multiplication and integral conversion.

Try doing the binary arithmetic on paper. The base-10 scaling doesn't work out to a shift or anything special… it's just a generic scaling operation.

Since the number is in the range [0,1], consider doing all the arithmetic in fixed point, perhaps using 1/1024 as the unit, or even in fixed point decimal with 1/1000 as the unit.

You should only use floating point math if you need more precision closer to zero.

Upvotes: 0

Related Questions