计算机基础1.-二进制总结

1.编码

正数 负数
原码 0本体 1本体
补码 0本体 按位取反+1(符号位始终为1)
反码 0本体 按位取反(符号位始终为1)

2.分类

有符号:
无符号:

3. 位运算

3.1 与 、或、异或

与(&) 0&0=0 1&0=0 1&1=1
或(|) 0|0=0 0|1=1 1|1=1
异或(^) 0^0=0 1^0=1 1^1=0

3.2 左移

m<<n

表示把m左移n位。往左移n位的时候,最左边的n位将被丢弃,同时在最右边补上n个0.

exp:

00001010<<2=00101000

10001010<<3=01010000

3.3 右移

m>>n

表示把m右移n位。往右移的时候,最右边的n位将被丢弃。

如果数字之前是一个正数,则右移之后在最左边补n个0;

如果数字之前是一个负数,则右移之后在最左边补n个1.

exp:

00001010>>2=00000010

10001010>>3=11110001

3.4 应用

3.4.1 移位运算代替乘除法
3.4.2 右移一位 == 除以2
3.4.3 左移一位 == 乘以2
二进制中1的个数
1
2
3
4
5
6
7
8
9
10
11

int NumberOf1(int n)
{
int count = 0;
while(n)
{
++count;
n = (n-1) & n;
}
return count;
}
不用加减法做加法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int Add(int num1,int num2)
{
int sum,carry;
do
{
sum = num1 ^ num2;
carry = (num1 & num2) << 1;
num1 = sum;
num2 = carry;
}
while(num2 !=0 );

return num1;
}
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

扫一扫,分享到微信

微信分享二维码
  • Copyrights © 2015-2020 John Doe
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信