位操作

1的补码和2的补码

1的补码:就是将原来2进制中的0变成1,1变成0.
2的补码:先将原来的0变成1,1变成0之后,再加上1.
如图:
1的补码
2的补码

位操作

1. 如何将二进制数中的某一位置为1

假设要将x的第position为置为1,那么:

(1)得到mask, mask = 1<<position
(2)x | mask

2. 如何将二进制数中的某一位置为0

条件同上,步骤:
(1)得到mask : mask = ~(1<<postion)
(2)x & mask

3. 如何翻转某一位,也就是如果是0变成1,如果是1变成0

步骤:
(1)得到mask : mask = 1<< postion;
(2) x ^mask

4. 如何判断第position位是否是1

步骤:
(1) 得到mask : mask = 1>> postion
(2)mask & 1;

5. 如何修改某一位为0或者为1

修改某一位的函数定义为:

def modify_set(x,position,state);//其中,x是要修改的数,position是修改第几位,state为0表示将postion设置为0,为1表示将postion为设置为1

此时步骤如下:
(1)得到mask : mask = 1<< postion
(2)(x&~mask)|(-state&mask)

6. 如何检查一个数是不是偶数?

答: (x&1) == 0;

7. 如何检查一个数是否是2的幂次方

答: (x&x-1) ==0

8. 如何快速交换两个数的位置

void swapXor(int& a, int& b)
 {
   a ^= b;
   b ^= a;
   a ^= b;
 }

9. 如何计算byte中1的个数

在java中可以使用:

int bitCount = Integer.bitCount(i);

10.计算一个数的绝对值

int myAbs(int x)
 {
   const int bit31 = x >> 31;
   return (x ^ bit31) - bit31;
 }

解释:
All major processors represent negative numbers using the two’s-complement which is defined as:
for x ≥ 0 → x
for x < 0 → NOT(x) + 1

On the lowest level, computers provide logical bit shifts and arithmetic bit shifts.
Both shifts differ in handling how to fill the empty bits on the left side.
Logical shifts insert zeros while arithmetic shifts replicate the formerly highest bit.

Whereas signed integers are arithmetically shifted in C, unsigned integers are logically shifted.

In our case x is shifted arithmetically 31 times to the right which basically erases its value
and spreads the highest bit. That means, line 3 evaluates either to 0x00000000 (→ 0) or
0xFFFFFFFF (→ −1).
Note: 32 bit systems require a shift by 31, 64 bit systems require a shift by 63 accordingly.

Consequently, line 4 turns out to be (x XOR 0) − 0 for positive values of x (including x=0).
x XOR 0 is still x and x − 0 remains x, too. So for positive x we get x ≥ 0 → x.

We saw that for negative values of x, bit31 is set to 0xFFFFFFFF.
Line 4 is then (x XOR 0xFFFFFFFF) − 0xFFFFFFFF. The bracketed XOR is equivalent to NOT(x) and
the constant −0xFFFFFFFF turns out to be −(-1) = +1.
In the end, the whole term is NOT(x) + 1, exactly what we wanted: for x < 0 → NOT(x) + 1

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值