#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv){
char i = -128;
int j = i;
printf("%d %u\n", j, j);
return 0;
}
result is -128 4294967168
what I think is
i: 10000000
and after the assignment operator, do the sign extension
j: 11111111 11111111 11111111 10000000
what I want to ask is how printf("%d",j) know to print -128 just use
the last byte? How it works?
Thx!
It doesn’t. It is told to print a signed
int, so it takes the appropriate number of bytes -typically 4 nowadays – from the stack and interprets that bit pattern as a signedint.When you assign a negative
charto anintvariable, as inint j = i;here, what happens is not really sign-extension, but – since all values acharcan represent are also representable as anint– a value-preserving conversion, thechariis converted to anintwith the same value.On two’s complement machines, which are by far the most common nowadays, and also in ones’ complement, that value-preserving conversion happens to coincide with sign-extension, but if the representaion is sign-and magnitude, the conversion would be different.
Since -128 isn’t representable as a signed eight-bit integer in ones’ complement or sign-and magnitude, let’s look at what happens to the bit-patterns when converting -127 to a 32-bit signed integer with the same kind of representation:
Two’s complement:
Ones’ complement:
Sign-and-magnitude: