Common Bit Tasks

本文深入解析了位运算的基本原理及其应用,通过实例展示了如何利用位运算解决编程问题。从位操作的基础概念出发,逐步介绍了位XOR、位与、位或、获取位、设置位、清除位等操作,并提供了相应的代码实现。此外,文章还探讨了如何通过位运算来清理特定位,以及如何高效地清除高位和低位。对于开发者来说,掌握这些技巧能显著提升代码效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1) If you XOR a bit with its own negated value, you will always get 1. Therefore thesolution to a ^ (~a)  will be the sequence of 1s.

consider a is of data-type byte.

example:

a = 00000001

~a  = 11111110

Now a ^ (~a) = 11111111

2) An operation like x & (~0 << n) clears the n rightmost bits of x. The value ~o is the sequences of 1s, so by shifting it by n, we have a bunch of ones followed by n zeros. By doing AND we clear the the rightmost n digits of x.

3) Bit Facts and Tricks:

x ^ 0′s = x                                       x & 0′s = 0                          x | 0′s = x

x ^ 1′s = ~x                                     x & 1′s = x                            x | 1′s = 1′s

x ^ x = 0                                         x & x = x                               x | x = x

4)  Get Bit :

If I want to get the bit at i-th position, this method shifts1 over by i bits , creating a value and performing an AND operation with the numbernum. If the resultant value is zero, that bit is unset else, that bit is set.

1
2
3
boolean getBit(int num,int i) {
    return((num & (1 << i)) != 0);
}

5) Set Bit:

If I want to set the bit at i-th position, this method shifts1 over by i bits , creating a value and performing an OR operation with the numbernum.

1
2
3
public int setBit(intnum, int i) {
    returnnum | (1 << i);
}

6) Clear Bit:

This method operates in reverse way as the setBit method works. To clear the i-th bit we first negate the result obtained from 1 << i and perform AND operation with the numbernum.

1
2
3
4
public int clearBit(intnum, int i) {
    intmask = ~(1 << i);
    returnnum & mask;
}

7) Clear all the MSB through i (inclusive) 高位到低位清零(包括低位)

This method is meant for clearing all the MSB’s (Most Significant Bits) through i (inclusive) we do:

1
2
3
4
public int clearBitsMSBThrough(intnum, int i) {
    intmask = ( 1 << (i + 1) ) - 1;
    returnnum & mask;
}

8) Clear all the bits from i through o(inclusive) 低位到0位清零 (包括低位)

This method is meant for clearing all the bits from i through 0 from the number num:

1
2
3
4
public int clearBitsIthrough0(intnum, int i) {
    intmask = ~(1 << (i + 1)) - 1;
    returnnum & mask;
}

转载于:https://www.cnblogs.com/duadu/p/6335496.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值