C ++中的位移位产生错误的答案 [英] Bitshifting in C++ producing the wrong answer

查看:73
本文介绍了C ++中的位移位产生错误的答案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试运行以下代码:

char c = (2 << 7) >> 7

应该返回0,因为2具有作为 char 的二进制表示形式:

which should return 0 because 2 has this binary representation as a char:

0 0 0 0 0 0 1 0

左移7位,我们得到

0 0 0 0 0 0 0 0

然后,在右移七班后,我们得到

Then, after seven shifts right, we get

0 0 0 0 0 0 0 0

但是,我得到的结果是2,而不是0.

However, I'm getting the result as 2, not 0.

编译器说 2<<7 是256,但它是 char ,因此不应为256.

The compiler says that 2 << 7 is 256, but it's a char and so it shouldn't be 256.

我了解 2<<7 将计算为 int s,答案将放入 c 中,因此 256>>7 是2.

I understand that the 2 << 7 will be calculated as ints and the answer will be put into c so 256 >> 7 is 2.

我试图将2强制转换为char(例如:(char)2>> 7 ),但是它也不起作用.

I tried to cast 2 to char (ex: (char)2>>7) but it doesn't work either.

我试图从 char 中提取每一位,所以我写了这段代码:

I'm trying to extract each bit from the char, so I wrote this code:

char c = 0x02;
for(int i=0;i<7;i++)
{
    char current = (c<<i)>>7;
}

我如何得到每一点?我的方式怎么了?

How can I get each bit? What's wrong with my way?

推荐答案

在C ++中,一个操作数为 int 的算术移位运算的结果始终为 int .因此,当您写

The result of an arithmetic shift operation with one operand being an int in C++ is always an int. Therefore, when you write

current = (c << i) >> 7;

C ++将解释(c<< i)(c<< i)>>7 作为 int s,仅在完成分配后才转换回 char .由于临时值是 int s,因此不会发生溢出,并且结果应为强制转换为 char 的整数结果.

C++ will interpret (c << i) and (c << i) >> 7 as ints, casting back to a char only when the assignment is done. Since the temporary values are ints, no overflow occurs and the result should come out to the integer result casted to a char.

希望这会有所帮助!

这篇关于C ++中的位移位产生错误的答案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆