Chop All American 6271 Posts user info edit post |
how do i turn a float value into a short int without losing precision?
for example, how do i go from this: float vhp[0] = 2.135
to this: short vhpBits[0] = 2135
multiply by 1000 won't work because there isn't always the same number of digits behind the decimal.
its been almost 10 years since i took C++, and i have to turn a simulink model in to C code by hand. the rtw generated code is much to bloated for use in the controller i'm programming. 4/18/2007 11:00:26 PM |
State409c Suspended 19558 Posts user info edit post |
What exactly are you trying to do? You want to keep all the precision, and then convert back to floating point at a later time? Which controller? 4/18/2007 11:12:15 PM |
Wolfmarsh What? 5975 Posts user info edit post |
There are multiple ways to do this, one possible way is to use the string class, convert the float to a string, and do a replace on the decimal, then convert to whatever you want.
Edit: Missed that you are working with some kind of micro, you may not have space for what i mentioned above.
[Edited on April 18, 2007 at 11:13 PM. Reason : missed the controller] 4/18/2007 11:12:27 PM |
qntmfred retired 40726 Posts user info edit post |
keep in mind also that if you have too many digits of precision, your result might not fall in the range of a short int
[Edited on April 18, 2007 at 11:17 PM. Reason : significant figures] 4/18/2007 11:17:05 PM |
Chop All American 6271 Posts user info edit post |
Quote : | "What exactly are you trying to do? You want to keep all the precision, and then convert back to floating point at a later time? Which controller?" |
not exactly. i'm starting with a floating point velocity, and need all the digits in integer form so it can eventually be fed into an algorithm that spits out current in counts (ie. counts/mA) to be sent to another mircro processor.
i don't remember the number of the microprocessor.
a short integer will allow for enough precision. the higher the number, the less precision i need.4/18/2007 11:56:28 PM |
skokiaan All American 26447 Posts user info edit post |
just copy the mantissa part of the float to your int.
http://www.artima.com/underthehood/floating.html
[Edited on April 19, 2007 at 12:20 AM. Reason : uiuoiuo] 4/19/2007 12:19:35 AM |
clalias All American 1580 Posts user info edit post |
yeah, frexp will return the binary significand. 4/19/2007 9:42:08 AM |
Chop All American 6271 Posts user info edit post |
didn't get a chance to work on it today, but thanks for the replies. after quick skim, that looks like it may work. any idea how long it takes to do that method to compute? i'm sampling at 1khz. 4/19/2007 10:09:45 PM |