问题签名 char c++
这是代码:
int main()
{
char c = 0x00;
//c |= 0x0A;
c |= 0xA0;
while(c != 0x00)
{
cout << (c & 1) << endl;
c = (c >> 1);
}
}
为什么当我使用 0X0A
而不是使用 0xA0
执行 or
时,此代码可以工作,因为数字 0xA0 太大了适合一个有符号的字符,但为什么我不允许设置 0xA0 的位?
当我打印循环时它永远不会中断并且只打印循环?怎么会?
This is the code:
int main()
{
char c = 0x00;
//c |= 0x0A;
c |= 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为执行右移时的符号扩展。
将
char c
替换为unsigned char c
或在移位后屏蔽 MSB。
请注意,
char
通常是有符号的(范围 -128..127),但某些 c/C++ 编译器将char
定义为unsigned
(AIX xlC 编译器是已知的情况)。It is because of the sign extension of when performing a right shift.
replace
char c
byunsigned char c
or mask the MSB after the shift.
Note that
char
is usually a signed (range -128..127) but some c/C++ compiler definechar
asunsigned
(AIX xlC compiler is known case).当右移负数时,您的实现必须在最高有效位添加 1(运算符的行为是实现定义的,因此通常取决于可用的 CPU 指令)。
第一次采样
c & 1
- 最低有效位 - 它实际上是 0。然后......将其移至 1101 0000,然后是 1110 1000, 1111 0111, 1111 1011, 1111 1101, 1111 1110, 1111 1111 - 这是然后稳定并且不再改变。因此,您不断打印 1,并且永远不会满足 c == 0 的终止条件。
好吧,它一开始就会打印几个 0,但你的屏幕可能会一眨眼就滚动过去,然后你就只能看到 1。
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).
The first time you sample
c & 1
- the least significant bit - it's actually a 0. Then......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.
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.