开发者

What are some great ways to take advantage of bitwise operators?

I constantly meet people using bitwise operators to do quick, easy and elegant things. I'd like to learn some useful tricks. What are some of the most useful bitwis开发者_运维百科e operator cases?


Constant time 2-exponentiation:

x = 1 << n; // x = pow(2, n)


While I agree with Michael McGowan in general, bit twiddling hacks can be very useful in certain situations, for instance when programming embedded hardware which doesn't have all the usual instructions. I've also had good use for such techniques when encoding programs into theorem provers such as SMT solvers, which didn't support all the operations I wanted to use.

My first stop when looking for a bitwise solution to a problem is the site bit twiddling hacks. It has quite a few code snippets for many of the most common techniques.

Then there's also the book Hacker's Delight covers a few bitwise techniques in depth.


I found some interesting bitwise operations collection at this place: http://graphics.stanford.edu/~seander/bithacks.html


Bitwise tricks (for non-Bitset Operation)

| Operator

Covert Upper Case to lower Case letter
     char A[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
     int n= strlen(A);
     for(int i=0;i<n;i++){
        if(A[i]>='A' && A[i]<='Z'){
            A[i] |= ' '; //A[i]=A[i]  | ' ';
        }
     }
     printf("%s\n",A);

Output

abcdefghijklmnopqrstuvwxyz

Explanation:

 ‘A’ = b01000001
|‘ ‘ = b00100000
----------------
       b01100001 =‘a’  

& Operator

Covert Lower Case to Upper Case Letter
     char A[] = "abcdefghijklmnopqrstuvwxyz";
     int n= strlen(A);
     for(int i=0;i<n;i++){
        if(A[i]>='a' && A[i]<='z'){
            A[i] &= '_';
        }
     }
     printf("%s\n",A);

Output

ABCDEFGHIJKLMNOPQRSTUVWXYZ

Explanation:**

 ‘a’ = b01100001
&‘_‘ = b11011111
----------------
       b01000001 =‘A’  
Determine if a Integer is odd or even
int n=100;
printf("%s\n", n&1?"odd":"even");
n=33;
printf("%s\n", n&1?"odd":"even");

Output:

even
odd

Explanation: (n&1) returns 1 if n is odd and returns 0 when it is even.

If n is odd the last bit of n in binary representation will be always 1. that is why when we & it with 1 the results become 1. If n is even the last bit of n in binary representation will be always 0. that is why when we & it with 1 the results become 0.

(eg. (odd) xxxxx1&1=1, (even) xxxxx0&1=0)

^ operator

Toggle Case
     char A[] = "AbCdEfGhIjKlMnOpQrStUvWxYz";
     int n= strlen(A);
     for(int i=0;i<n;i++){
        A[i] ^= ' ';
     }
     printf("%s\n",A);

Output

aBcDeFgHiJkLmNoPqRsTuVwXyZ

Explanation:**

 ‘A’ = b01000001
^‘ ‘ = b00100000
----------------
       b01100001 =‘a’  

 ‘a’ = b01100001
^‘ ‘ = b00100000
----------------
       b01000001 =‘A’  

Swap two number without temp
int x=12, y=20;
printf("%d %d\n",x, y);
x^=y;   //x=x^y
y^=x;   //y=x^y
x^=y;   //x=x^y
printf("%d %d\n",x, y);

Output:

12 20
20 12

**Explanation: **

x=12 y=20
now for x=x^y
 12 = b01100
^20 = b10100
-------------
  x = b11000

now for y=x^y
  x = b11000
^20 = b10100
-------------
  y = b01100 =12 (swapped)

now for y=x^y
  x = b11000
 ^y = b01100
-------------
  x = b10100 =20 (swapped)

<< operator

Multiply by 2n
int n=3;
int b = 4<<n;
printf("%d\n",b);

Output: 32

Explanation: 4x23 =32

4 in binary 100
100<<3 (right shift 3 times) will be 100000
100000 is equivalent to 32
Set value 2n
int n=3;
int b = 1<<n;
printf("%d\n",b);

Output: 8

Explanation: 1*23 =8

>> operator

Divide by 2n
int n=3;
int b = 32>>n;
printf("%d\n",b);

Output: 8

Explanation:

What are some great ways to take advantage of bitwise operators?

32 in binary 100000
100000>>3 (left shift 3 times) will be 000100
100 is equivalent to 4


Usually it's not a good idea to use such tricks. Modern compilers often do this kind of stuff behind the scenes when possible. That said, sometimes you have knowledge that the compiler doesn't (maybe that a particular value is guaranteed at runtime to be a power of 2). If you determine that it is a good idea to try such tricks, here are useful bit twiddling hacks.


You can always make use of left shift bitwise operator (<<) to mutiply the given number by 2.
For Ex -

   public class abc {public static void main (String[] arg)
{
    int a = 650;
    int doubleOfa = a<<1;
    System.out.println(a);
    System.out.println(doubleOfa);

    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜