Casting float to unsigned short | Sololearn: Learn to code for FREE!

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.

4/14/2021 4:44:54 AM

ogoxu

9 Answers

New Answer

+1

I guess I found my answer: https://stackoverflow.com/questions/10541200/is-the-behaviour-of-casting-a-negative-double-to-unsigned-int-defined-in-the-c-s

+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.

+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).

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);

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`.

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?

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.

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.

0

Yeah that makes sense 👍