为什么组合uint8_t有两个变化产生不同的结果? [英] Why does combining two shifts of a uint8_t produce a different result?

查看:133
本文介绍了为什么组合uint8_t有两个变化产生不同的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能解释我为什么:

x = x << 1;
x = x >> 1;

x = (x << 1) >> 1;

生产用C不同的答案? X 是一个* uint8_t有*类型(无符号的1字节长的整数)。例如,当我将它传递 128(10000000)在返回第一种情况如预期最显著位跌倒 0 (出),而在第二种情况下它返回原来的 128 。这是为什么?我期望这些前pressions是等价的?

produce different answers in C? x is a *uint8_t* type (unsigned 1-byte long integer). For example when I pass it 128 (10000000) in the first case it returns 0 (as expected most significant bit falls out) but in the second case it returns the original 128. Why is that? I'd expect these expressions to be equivalent?

推荐答案

这是由于整数促销,逐位变化的两个操作数会在两种情况下晋升的 INT 的。在第二种情况:

This is due to integer promotions, both operands of the bit-wise shifts will be promoted to int in both cases. In the second case:

x = (x << 1) >> 1;

X&LT的结果;&LT; 1 将是一个的 INT 的,因此,移位将是preserved和可用到下一步骤为 INT 的其中将转向其再次回来。在第一种情况:

the result of x << 1 will be an int and therefore the shifted bit will be preserved and available to the next step as an int which will shift it back again. In the first case:

x = x << 1;
x = x >> 1;

当您分配回 X 你将失去额外的比特。从草案C99标准部分 6.5.7按位移位运算符它说:

when you assign back to x you will lose the extra bits. From the draft C99 standard section 6.5.7 Bit-wise shift operators it says:

整数促销活动在每个操作数执行。

The integer promotions are performed on each of the operands.

整数促销活动将在第 6.3.1.1 布尔,字符和整数的段落的 2 的它说

The integer promotions are covered in section 6.3.1.1 Boolean, characters, and integers paragraph 2 which says:

如果int可以重新present原始类型的所有值,该值被转换为int;
  否则,将其转换为一个unsigned int。这些被称为整数
  促销活动。 48)

If an int can represent all values of the original type, the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions.48)

最后一块这个为什么转换过程中的 INT 的值 256 来的 uint8_t有的给我们 0 ?转换是覆盖在部分 6.3.1.3 符号和无符号整数的是下的转换的部分,说:

The last piece of this why does the conversion from the int value 256 to uint8_t give us 0? The conversion is covered in section 6.3.1.3 Signed and unsigned integers which is under the Conversions section and says:

否则,如果新类型是无符号的值是通过反复增加或转换
  减去超过可重新$ P $在新型psented最大值多一个
  直到该值是在新的类型的范围。 49)

Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.49)

因此​​,我们有 256 - (255 + 1) 0

这篇关于为什么组合uint8_t有两个变化产生不同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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