移位运算

计算机中的数都是以二进制存储,位运算是直接对二进制数进行操作的运算,它的速度非常快。

移位运算是其中比较常用的。

1. 移位运算分为 逻辑移位 和 算术移位。

逻辑移位,是不管往哪边移动,都用0来补齐。

算术移位:算术左移,用0补齐。算术右移,用符号位来补齐。

注意:将移位区分为逻辑移位和算术移位的原因是,不希望移位运算影响数本来的正负性。

2. 移位运算最常见用法,做”乘除法“。

无论是神马类型的移位,记住一点,【左移乘法,右移除法】

x<<n: x·2n  ;  x>>n:x/2n

use 8 unsigned bits to represent number 5 : 00001001

5>>1:   00000101 ---> 00000010 :  5 ---> 2   【右移1位】相当于【除以2】

5<<1:   00000101 ---> 00001010 :  5 ---> 10  【左移1位】相当于【乘以2】

3. 数在计算机中用补码存储。

牢记这一点! 正数的补码就是原码;负数的补码是其正数的反码+1

Ex.  Find the two’s complement representation of –6

Step1: find binary representation in 8 bits

  6 = 00000110

 Step 2: Complement the entire positive number, and then add one

                                 00000110  

(complemented)  ->    11111001

(add one)  ->  +                      1

                                 11111010

So:  -6 = 11111010  (in 2's complement form, using any of above methods)

另一种方法是,

Scan binary representation from right too left, find first one bit, from low-order (right) end, and complement the remaining pattern to the left.

                                      00000110  

(left complemented)  -->  11111010

原文地址:https://www.cnblogs.com/renrenbinbin/p/4337552.html