| 
View
 

BitwiseOps

This version was saved 17 years, 2 months ago View current version     Page history
Saved by Kenneth Finnegan
on April 1, 2008 at 5:00:20 pm
 

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)

<< - left shift

>> - right shift

~ - one's complement

 

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.

 


Sources:

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

Comments (0)

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