Common Bit Tasks

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( int num, int i) {
    return num | ( 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( int num, int i) {
    int mask = ~( 1 << i);
    return num & 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( int num, int i) {
    int mask = ( 1 << (i + 1 ) ) - 1 ;
    return num & 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( int num, int i) {
    int mask = ~( 1 << (i + 1 )) - 1 ;
    return num & mask;
}

你可能感兴趣的:(位运算)