-1
int main(void)
    {
        char x1 = 0x81;
        char x2 = 0x1;
        int a, b;
        a = x1+x2;
        b = (a>>8) & 0xFF;

        printf("a = %d, b = %d",a, b);
        return 0;
    }

Why do I get the results a = -126 and b = 255 ?

x1 is 1000 0001

x2 is 0000 0001

Sum = 1000 0010, thus it's 130. But, because it's the case with "char", 130 exceeds the maximum possible value represented on 8 bit (128). What can I do in this case ? Thanks.

wonderingdev
  • 1,132
  • 15
  • 28
  • 2
    Why don't you use `unsigned char`? – haccks Jun 04 '15 at 09:07
  • @haccks So is the exercise. It's required to determine the result without using computer – wonderingdev Jun 04 '15 at 09:08
  • 3
    The default signedness of an untyped `char` is implementation defined: [Is char signed or unsigned by default?](http://stackoverflow.com/questions/2054939/is-char-signed-or-unsigned-by-default). What implementation does "without using computer" use? – Jongware Jun 04 '15 at 09:27

3 Answers3

1
  1. Simply x1+x2 is 1000 0010
  2. When the result is stored into signed integer the sign is extended, therefore a is 1111 1111 1000 0010 which is 126D in two's compliment format. Almost all computers stores negative number in two's compliment format. Therefore a is interpreted as -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 as 32-bit.

  2. Negative number is represented in 2's compliment format.

Vagish
  • 2,520
  • 19
  • 32
1

In C by default char declaration is signed char(-127 to +127). If you want to increase the range then you have to make it unsigned char (0 to +255)

So following code snippet will work for you

int main()
{
    unsigned char x1 = 0x81;
    unsigned char x2 = 0x1;
    int a, b;
    a = x1+x2;
    b = (a>>8) & 0xFF;
    printf("a = %d, b = %d",a, b);        
    return 0;
}
Amol Saindane
  • 1,568
  • 10
  • 19
  • 1
    Your first sentence is wrong. "**The implementation** shall define `char` to have the same range, representation, and behavior as either `signed char` or `unsigned char`" (ISO/IEC 9899:201x Draft, April 2011 [my emphasis]). – Jongware Jun 04 '15 at 10:20
0

Although you initialize the signed char variable with 0x81 it has a value that depends on its data type. The patter 0x81 is the representation of -127.

When you add -127 and 1 you get the sum -126. 1000 0010

The result expires an integer promotion to the result type signed int. In this phase the sign is expanded to the new data type. 1111 1111 1000 0010. The upper bits are the values that you see in b.

harper
  • 13,345
  • 8
  • 56
  • 105