Here is what causes me frustration:
We have two integers: the one is of type int16_t and the other is int8_t. I have initialized both variables as follows:
int8_t short_int = 250 //This equals -6, and its binary representation is 0b1111 1010
So far so good.
int16_t my_int = short_int //as we already know short_int is 0b1111 1010
For me, my_int should equal to 0b1111 1010 right? As 16bit integer the value 0b1111 1010 has a decimal representation of 250. OK, but it doesn't.
Printing the value of my_int I get -6 which in binary representation is 0b1111 1111 1111 1010 totally different from short_int as a binary.
int8_t short_int = 250 causes implementation-defined behaviour. The range of int8_t is -128 through 127.
Apparently your implementation generates the value -6 for short_int here. OK so far.
But now you have to remember that C has value-preserving conversions. If you convert -6 to any other signed integral type it will still be -6, regardless of what its bit representation is.
Some people will talk about "sign extension" and other such stuff, however to understand how C works you just have to remember that the value is preserved unless it is out of range for the type; in which case it is either truncated (for unsigned types) or implementation-defined behaviour (for signed types; usually 2's complement truncation).
C works based on values not on bit-patterns.
If you assign an int8_t to an int16_t, both have the same value afterwards.
For negative values this means they have a different bit pattern (assuming a common representation of negative values).
Note that your int8_t is in fact negative.
Use:
int16_t my_int = (uint8_t) short_int;
instead of:
int16_t my_int = short_int;
short_int is a negative signed integer so it undergoes sign extension when converted to int16_t.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With