• If you are citizen of an European Union member nation, you may not use this service unless you are at least 16 years old.

  • You already know Dokkio is an AI-powered assistant to organize & manage your digital files & messages. Very soon, Dokkio will support Outlook as well as One Drive. Check it out today!



Page history last edited by Kenneth Finnegan 14 years, 11 months ago

Bitwise operations tend to be confusing because it uses some of the more cryptic symbols on the keyboard and what they do is less clear.



& - AND

| - inclusive OR (This is a pipe, SHIFT-\)

^ - exclusive OR (XOR)

~ - one's complement

<< - left shift

>> - right shift




Input 1 Input 2 Output
0 0 0
0 1 0
1 0 0
1 1 1



x = x & 0177;

This will set every bit above the bottom 7 to 0, then save the lower 7 to their original state.



Input 1 Input 2 Output
0 0 0
0 1 1
1 0 1
1 1 1



x = x | 0177;

This will set the bottom 7 bits to 1, and retain the rest from x.



Input 1 Input 2 Output
0 0 0
0 1 1
1 0 1
1 1 0


Note the difference from inclusive OR by its behavior with two 1 inputs.



x = x ^ 0177;

This will reverse the bottom 7 bits of x. 

The advantage of ^ versus | is that you can get the original input again by XORing with the same number.

x == ( (x ^ 0177) ^ 0177)

This property means that XOR is used extensively in encryption applications.



This is like XOR, but with only one number.  It reverses every bit, so 0110 would become 1001.



x = ~077;

This will set every bit in x to 1 except the bottom 6.  This is an advantage because it doesn't matter what the word size of x is.

x = 0177700; Assumes x is a 16 bit value, if x is changed to a 32 or 64 bit value, you would have to go through and change every piece of code making assumptions about word size.



These two commands are probably the one's I use the most of any on this page.  They shift the bits either left or right by the number given to it, then usually fills the rest with 0s.



x = x<<2;

This would be equivalent to multiplying x by 4.



When you're right shifting an unsigned interger, the empty bits will be filled with 0s.  When you're right shifting a signed interger, the results are less predictable and, depending on the machine, will either fill it with 0s or 1s.


For a huge list of possible uses for bitwise operations, see http://graphics.stanford.edu/~seander/bithacks.html



The C Programming Language 2nd Ed., Kernighan & Ritchie, pg. 48-49.

Comments (0)

You don't have permission to comment on this page.