Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

rhino2876

Bitwise Operators question

This topic is 6024 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
Advertisement
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.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
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.

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!