c - Working with bits. Overflow -
int main(void) { char x1 = 0x81; char x2 = 0x1; int a, b; = x1+x2; b = (a>>8) & 0xff; printf("a = %d, b = %d",a, b); return 0; }
why results = -126 , b = 255 ?
x1 1000 0001
x2 0000 0001
sum = 1000 0010, it's 130. but, because it's case "char", 130 exceeds maximum possible value represented on 8 bit (128). can in case ? thanks.
- simply
x1+x2
1000 0010
- when result stored
signed integer
sign extended, thereforea
1111 1111 1000 0010
126d
in two's compliment format. computers stores negative number in two's compliment format. thereforea
interpreted-126
. - now
b = (1111 1111 1000 0010 >> 8 ) & (0000 0000 1111 1111)
thereforeb = 0000 0000 1111 1111 = 255d
.
assumptions:
your compiler treats integer 32-bit.
negative number represented in 2's compliment format.
Comments
Post a Comment