Reputation: 107
I was wondering how type casting works in practice between types (in "embedded" C). For example: if I have a Signed 16-bit
number with value -80d
, 11010000b
, and i want to cast it into unsigned 16-bit
. which value do i get, would it be just 80d, or would it be 208.
what i mean is, is the conversion bitwise or arithmic? does just the interpretation of the bits change, or does the conversion really change the bits?
if it does really change the bits, how would i have to do it in such a way just the interpretation changes.This would be done for example when i read a u8 value from an i2c device and have to interpret the bits as a signed value.
Lastly, actually the same as above: if it does not change the bits, how would i cast it so it changes the bits and not the values?
Kind regards, Jesse
Upvotes: 1
Views: 267
Reputation: 214495
Whenever you make a cast, you trigger a type conversion, which is specified by C11 6.3.1.3:
6.3.1.3 Signed and unsigned integers
When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.
Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.60)
Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.
The procedure of converting from signed to unsigned is covered by the second paragraph. It is written in this weird way to cover all manner of signedness formats. What it means in practice on a 16 bit two's complement system, is that from -80d
(hex FFB0h
) you end up with the value FFB0h
, which is the unsigned number 65456d
.
It doesn't change any bits.
Upvotes: 4