带符号和无符号的位移操作 [英] Bitshift operation with signed and unsigned

查看:34
本文介绍了带符号和无符号的位移操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在对 int 进行位移操作,但很惊讶它没有按预期输出.

I was doing a bitshift operation of an int and was surprised that it didn't come out as expected.

int i, res;
i = 0x80000000;
res = i>>1;                //results in 0xc0000000
res = (unsigned int) i>>1; //results in 0x40000000

整数中的一位移位怎么可能只适用于第 31 位?

how is it possible that a shift of a bit in an integer does only work to the 31st bit?

推荐答案

您所看到的可能是 算术位移位.

右移时,最左边的位(通常是有符号整数表示)被复制以填充所有空缺职位(这是一种符号扩展).

when shifting to the right, the leftmost bit (usually the sign bit in signed integer representations) is replicated to fill in all the vacant positions (this is a kind of sign extension).

C99 标准 6.5.7§5 说:

The C99 standard 6.5.7§5 says:

E1 >> E2 的结果是 E1 右移 E2 位位置.[...] 如果 E1 具有有符号类型和负值,则结果值是实现定义的.

The result of E1 >> E2 is E1 right-shifted E2 bit positions. [...] If E1 has a signed type and a negative value, the resulting value is implementation-defined.

所以结果可以是编译器作者决定的任何东西.他们可能决定扩展符号位,编译器文档应该提到它.

So the result could be anything the compiler writers decided it to be. They probably decided to extend the sign bit, the compiler doc should mention it.

这篇关于带符号和无符号的位移操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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