0

Casting float to unsigned short

Hi everyone, I've got a strange bug with my system. I have a float struct member which I divide with a float resolution value. Then I cast it to an unsigned short so that I can put it in a two bytes message. Like this: float calc, num = -150.35, res = 0.703125; unsigned short val; val = (unsigned short)(num / res); msg_1 = val >> 8; msg_2 = val; The problem here, with a positive num variable, I cast it to the val successfully; with a negative one, val is 0 no matter what is the num's value. I couldn't find out why. But when I changed the type of val to signed short, I managed to calculate the result successfully for both of the positive and the negative values. But I'm not sure if this is healthy for messages. I usually use unsigned short and unsigned char without knowing why.

14th Apr 2021, 4:44 AM
ogoxu
ogoxu - avatar
9 ответов
+ 2
There is a reason why "unsigned short" is named "unsigned" whenever a data type is unsigned, it means only positive values can be stored in it as there is no space reserved to store the "sign"( positive/negative ) of the number.
14th Apr 2021, 4:58 AM
Arsenic
Arsenic - avatar
+ 1
Powehi, Your question topic was about type casting from `float` to `unsigned int`. The way you can print an `unsigned int` using a format specifier intended for `int` isn't an actual example to the topic (type casting). And for signed integers, as you probably know already, the number of usable bits to represent a value is subtracted by one, as the MSB is acting as the sign bit (signed 7bits, unsigned 8bits). And please don't forget, there's a risk of data loss when cast from a higher ranked type to a lower ranked type, `float` usually takes 4 bytes (higher ranked), `unsigned short` usually takes 2 bytes (lower ranked).
14th Apr 2021, 7:03 AM
Ipang
0
Arsenic false. You can store all the bits in the unsigned data anyway. u can try : int x = -5; unsigned int y = x; printf("%d",y);
14th Apr 2021, 5:13 AM
ogoxu
ogoxu - avatar
0
Powehi Wrong, you are using %d for printing an `unsigned int` variable when you should've used %u, the correct format specifier used for printing/reading `unsigned int`.
14th Apr 2021, 5:51 AM
Ipang
0
Ipang I obviously know. It's just pointing out that the data can be stored as-is. It's just ignoring the sign bit or not. The system is coded with C99. Maybe relevant?
14th Apr 2021, 6:00 AM
ogoxu
ogoxu - avatar
0
I mean, let's talk about bytes. 1111 1111 -> if unsigned; 255 1111 1111 -> if signed; -1 Whether signed or unsigned, there are 8 bits. And you can converse these. Assigning -1 to an unsigned char, means assigning 255.
14th Apr 2021, 6:08 AM
ogoxu
ogoxu - avatar
0
Thanks Ipang, I am aware of the data-loss. Just can't figure out the way the system calculates 0. Doesn't make any sense + with other IDE's the casting is OK, the result it successfully calculated.
14th Apr 2021, 7:17 AM
ogoxu
ogoxu - avatar
0
Yeah that makes sense 👍
14th Apr 2021, 7:29 AM
Ipang