Bitwise Operators question
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.
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.
April 19, 2002 01:10 PM
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.
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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement