有符号整数的算术位移 [英] Arithmetic bit-shift on a signed integer

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

问题描述

我试图弄清楚算术位移运算符在 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

阅读 Stack Overflow 和一些网站上的其他帖子,我发现:<< 将移向 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.

并且 >> 将移向 LSB(在我的例子中向右)并用 MS 位填充空"位

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

所以,x = x <<7 将导致将 LSB 移动到 MSB,并将所有内容设置为 0.

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

1000.0000

现在,假设我会 >>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 位旨在表示有符号的 8 位值(在切换到 8 位示例之前,您正在谈论有符号的 32 位整数"),那么您将得到一个负数.右移可能会用原始 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.)

unsigned 值的相同操作在两种情况下都有明确定义:空"位将填充为 0.

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

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

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