查看左移、右移的源代码
←
左移、右移
跳转至:
导航
、
搜索
因为以下原因,你没有权限编辑本页:
您刚才请求的操作只有这个用户组中的用户才能使用:
用户
您可以查看并复制此页面的源代码:
左移运算(<<),右移运算(>>)<br> 描述<br> From The Bitmath Tutorial in The Playground <br> 在C++中有两个移位运算符:左移运算符<<和右移运算符>>。这些运算符将使左边操作数的每一位左移或右移其右边指定的位数。<br> 语法<br> <pre style="color:blue"> variable << number_of_bits variable >> number_of_bits 参数<br> *variable - (byte, int, long) number_of_bits integer <= 32 <br> 示例:<br> <pre style="color:green"> int a = 5; // binary: 0000000000000101 int b = a << 3; // binary: 0000000000101000, or 40 in decimal int c = b >> 3; // binary: 0000000000000101, or back to 5 like we started with </pre> 当把x左移y位(x << y),x中最左边的y位将会丢失。 <pre style="color:green"> int a = 5; // binary: 0000000000000101 int b = a << 14; // binary: 0100000000000000 - 101中的第一个1被丢弃 </pre> 如果您确信没有值被移出,理解左移位运算符一个简单的办法是,把它的左操作数乘2将提高其幂值。例如,要生成2的乘方,可以使用以下表达式: <pre style="color:red"> 1 << 0 == 1 1 << 1 == 2 1 << 2 == 4 1 << 3 == 8 ... 1 << 8 == 256 1 << 9 == 512 1 << 10 == 1024 ... </pre> 当把x右移y位,x的最高位为1,该行为依赖于x的确切的数据类型。如果x的类型是int,最高位为符号位,决定x是不是负数,正如我们在上面已经讨论过的。在这种情况下,符号位会复制到较低的位: <pre style="color:green"> int x = -16; // binary: 1111111111110000 int y = x >> 3; // binary: 1111111111111110 </pre> 该行为,被称为符号扩展,常常不是你所期待的。反而,你可能希望移入左边的是0。事实上右移规则对于无符合整型表达式是不同的。所以你可以使用强制类型转换来避免左边移入1。 <pre style="color:green"> int x = -16; // binary: 1111111111110000 int y = (unsigned int)x >> 3; // binary: 0001111111111110 </pre> 如果你可以很小心地避免符号扩展,你可以使用右移位运算符>>,作为除以2的幂的一种方法。例如 <pre style="color:green"> int x = 1000; int y = x >> 3; // 1000除以8,得y = 125. </pre>
返回
左移、右移
。
导航菜单
个人工具
登录
名字空间
页面
讨论
变换
查看
阅读
查看源代码
查看历史
操作
搜索
导航
首页
社区专页
新闻动态
最近更改
随机页面
帮助
工具箱
链入页面
相关更改
特殊页面
页面信息