• ### What is your GameDev Story?

Public Group

#### Archived

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

# Bitwise Operators question

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

## 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 on other sites
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 on other sites
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 on other sites
Cool, thanks a bunch.

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 17
• 14
• 10
• 9
• 11
• ### Forum Statistics

• Total Topics
634094
• Total Posts
3015498
×