Advertisement

Bitwise Operators question

Started by April 19, 2002 12:50 PM
2 comments, last by rhino2876 22 years, 6 months ago
Somebody please explain the following to me from the K&R book. Also, what does it mean when a numbers starts with a 0 such as the below 0177? The bitwise AND operator & is often used to mask off some set of bits, for example n = n & 0177; sets to zero all but the low-order 7 bits of n.
Rhino2876
Numbers starting with 0 in C are octal instead of decimal or hexadecimal. Each place in the octal number can be between 0 and 7. 0177 oct = 0x7F hex = 127 dec = 0111 1111 bin.

The & operator is the "bitwise and" operator, which will perform the and operation bit-by-bit between two integers:
0 and 0 = 0
0 and 1 = 0
1 and 0 = 0
1 and 1 = 1

The operation above (n = n & 0177) will therefore clear all but the last seven bits of n.
Advertisement
A leading 0 means the number is Octal, as in base 8. Likewise a leading 0x would mean Hex, base 16. In Octal each digit is represented by 3 bits. So 0177 is equivilent to 001 111 111 in binary (remember the first 0 just means it is Octal so no need to include it).
What n = n & 0177 does is a bitwise & operation on each bit of n with the Octal 0177. It would look like this:

n = 000 000 000
0177 = 001 111 111 &
---------------------
n = 001 111 111

So see, all but the low-order 7 bits of n are set to zero.
Cool, thanks a bunch.
Rhino2876

This topic is closed to new replies.

Advertisement