Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic integer assignment

Tags:

c

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.

like image 405
Radoslaw Krasimirow Avatar asked Apr 24 '15 12:04

Radoslaw Krasimirow


3 Answers

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

like image 182
M.M Avatar answered Nov 03 '22 13:11

M.M


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.

like image 25
undur_gongor Avatar answered Nov 03 '22 15:11

undur_gongor


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.

like image 2
ouah Avatar answered Nov 03 '22 14:11

ouah