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.

  1. simply x1+x2 1000 0010
  2. when result stored signed integer sign extended, therefore a 1111 1111 1000 0010 126d in two's compliment format. computers stores negative number in two's compliment format. therefore a interpreted -126 .
  3. now b = (1111 1111 1000 0010 >> 8 ) & (0000 0000 1111 1111) therefore b = 0000 0000 1111 1111 = 255d.

assumptions:

  1. your compiler treats integer 32-bit.

  2. negative number represented in 2's compliment format.


Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - Bypass Geo Redirect for specific directories -

php - .htaccess mod_rewrite for dynamic url which has domain names -