Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int16_t to float conversion weirdness

Tags:

c++

c

I am at a loss with what is happening here. I need to convert a float to an int16_t and back. Here is the syntax:

int16_t val = (int16_t)round((float)0xFFFE/100 * angle);
//and back
float angle = ((float)100/0xFFFE * val;

When I use an initial angle value of -0.093081, it converts back. But when I use 182.241211 it converts back to -17.764824?

Any idea what is going on?

like image 976
JonnyCplusplus Avatar asked Apr 10 '26 15:04

JonnyCplusplus


1 Answers

0xFFFE is almost the maximum 16-bit number; and only for an unsigned 16-bit number, at that. If you divide it by 100 and then multiply by 182, it's definitely going to overflow.

Let's do it fully in base 10 for clarity (0xFFFE is 65534):

65534 / 100 *  -0.093081 =    -60.99970254
65534 / 100 * 182.241211 = 119429.95521674

The full range of your signed 16-bit integer is almost certainly [-32768, 32767]. That last result won't fit.

like image 104
Carl Norum Avatar answered Apr 13 '26 05:04

Carl Norum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!