经签署的整数运算位移位 [英] Arithmetic bit-shift on a signed integer

查看:120
本文介绍了经签署的整数运算位移位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出在C位移运营商究竟运算的工作,以及它将如何影响符号的32位整数。

I am trying to figure out how exactly arithmetic bit-shift operators work in C, and how it will affect signed 32-bit integers.

为了简单起见,假设我们在一个字节中工作(8位):

To make things simple, let's say we work within one byte (8 bits):

x = 1101.0101
MSB[ 1101.0101 ]LSB

阅读堆栈溢出和一些网站其他职位,我发现:
<< 将走向MSB转移(到左侧,在我的情况),并填写0空LSB位

Reading other posts on Stack Overflow and some websites, I found that: << will shift toward MSB (to the left, in my case), and fill "empty" LSB bits with 0s.

&GT;&GT; 将走向移动LSB(向右,在我的情况),并填写空与MS位bit

And >> will shift toward LSB (to the right, in my case) and fill "empty" bits with MS bit

因此​​, X = X&LT;&LT; 7 将导致移动LSB到MSB,一切都设置为0。

So, x = x << 7 will result in moving LSB to MSB, and setting everything to 0s.

1000.0000

现在,让我们说我会&GT;&GT; 7 ,最后的结果。这将导致 [0000.0010] ?我说得对不对?

Now, let's say I would >> 7, last result. This would result in [0000.0010]? Am I right?

我是对的我对移位运算符假设?

Am I right about my assumptions about shift operators?

我只是在我的机器上测试,**

I just tested on my machine, **

int x = 1;   //000000000......01

x = x << 31; //100000000......00

x = x >> 31; //111111111......11 (Everything is filled with 1s !!!!!) 

为什么?

推荐答案

负符号数的右移具有实现定义的行为。

Right shift of a negative signed number has implementation-defined behaviour.

如果您的8位是为了重新present一个符号的8位值(如你在谈论一个符号的32位整数切换到8位的例子之前),那么你有一个负数。转移它的权利可以填写与原来的MSB空位(即执行符号扩展),也可以在零转移,具体取决于平台和/或编译器。

If your 8 bits are meant to represent a signed 8 bit value (as you're talking about a "signed 32 bit integer" before switching to 8 bit examples) then you have a negative number. Shifting it right may fill "empty" bits with the original MSB (i.e. perform sign extension) or it may shift in zeroes, depending on platform and/or compiler.

(实现定义的行为意味着,编译器会做一些合理的,但在一个平台依赖的方式;该编译器文档应该告诉你什么)

(Implementation-defined behaviour means that the compiler will do something sensible, but in a platform-dependent manner; the compiler documentation is supposed to tell you what.)

一个左移,如果号码或者开出负,或换档操作将一个1移向或超出符号位,具有不确定的行为(如做符号值而导致溢出最操作)。

A left shift, if the number either starts out negative, or the shift operation would shift a 1 either to or beyond the sign bit, has undefined behaviour (as do most operations on signed values which cause an overflow).

(未定义行为意味着什么都可能发生。)

(Undefined behaviour means that anything at all could happen.)

上相同的操作的无符号的值是在这两种情况下明确定义:空位将被填充0

The same operations on unsigned values are well-defined in both cases: the "empty" bits will be filled with 0.

这篇关于经签署的整数运算位移位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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