开发者

problem signed char c++

This is the code:

int main()
{

 char c = 0x00;
 //c |= 0x0A;
 c |=开发者_JS百科 0xA0;

 while(c != 0x00)
 {
  cout << (c & 1) << endl;
  c = (c >> 1); 
 }
}

Why does this code work when I do or with 0X0A and not with 0xA0, as a number 0xA0 is to big to fit a signed char but why am I not allowed to set the bits for 0xA0?

When I print the loop it never breaks and it only print ones? How come?


It is because of the sign extension of when performing a right shift.

0xA0 <=>        10100000 binary (and is a negative number because the MSB is set to 1)
(0xA0 >> 1) <=> 11010000

replace char c by unsigned char c or mask the MSB after the shift.

int main()
{

 char c = 0x00;
 //c |= 0x0A;
 c |= 0xA0;

 while(c != 0x00)
 {
  cout << (c & 1) << endl;
  c = (c >> 1) & 0x7f; 
 }
}

Note that char is usually a signed (range -128..127) but some c/C++ compiler define char as unsigned (AIX xlC compiler is known case).


Your implementation must add a 1 in the most significant bit when right-shifting a negative number (the operator's behaviour is implementation defined, so usually depends on which CPU instructions are available).

0xA0 = 1010 0000 binary

The first time you sample c & 1 - the least significant bit - it's actually a 0. Then...

c = (c >> 1)

...shifts this to 1101 0000, then 1110 1000, 1111 0111, 1111 1011, 1111 1101, 1111 1110, 1111 1111 - which is then stable and never changes further. Hence, you keep printing 1s and never satisfy the termination condition of c == 0.

When I print the loop it never breaks and it only print ones? How come?

Well, it will have printed a few 0s at the very start, but your screen's probably scrolled past them in a blink and thereafter you only see the 1s.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜