为什么将int a = 1左移31位然后右移31位,它变为-1 [英] why shift int a=1 to left 31 bits then to right 31 bits, it becomes -1

查看:739
本文介绍了为什么将int a = 1左移31位然后右移31位,它变为-1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给予

int a = 1;(00000000000000000000000000000001),

我所做的只是

a=(a<<31)>>31;

我认为在此声明之后,a仍应为1(我认为没有改变).但是,结果为-1(11111111111111111111111111111111).有人知道为什么吗?

I assume a should still be 1 after this statement (nothing changed I think). However, it turns out to be -1 (11111111111111111111111111111111). Anyone knows why?

推荐答案

您缺少的是在C ++中,右移>>是实现的定义.对于有符号值,它可以是逻辑移位或算术移位.在这种情况下,它会从左侧向左移动1,以保留已移动值的符号.通常,除非您确切地知道有符号的值将是正数或该移位的实现无关紧要,否则您要避免对它们进行移位.

What you are missing is that in C++ right shift >> is implementation defined. It could either be logical or arithmetic shift for a signed value. In this case it's shifting in 1s from the left to retain the sign of the shifted value. Typically you want to avoid doing shifts on signed values unless you know precisely that they will be positive or that the shift implementation doesn't matter.

这篇关于为什么将int a = 1左移31位然后右移31位,它变为-1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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