| 
View
 

BitwiseOps

Page history last edited by Kenneth Finnegan 16 years 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.

 

Code:

& - AND

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

^ - exclusive OR (XOR)

~ - one's complement

<< - left shift

>> - right shift

 


 

AND:

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

 

Usage:

x = x & 0177;

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

 

INCLUSIVE OR:

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

 

Usage:

x = x | 0177;

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

 

EXCLUSIVE OR (XOR):

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.

 

Usage:

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.

 

ONE'S COMPLIMENT:

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

 

Usage:

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.

 

LEFT AND RIGHT SHIFT:

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.

 

Usage:

x = x<<2;

This would be equivalent to multiplying x by 4.

 

Note:

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

 


Sources:

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

Comments (0)

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