# Need help understanding this one: file_walker += (size+3)&~0x3;

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

## Recommended Posts

Hi guys,

As the subject says, I'm studying old code for 90's game and came to a line that my limited c++ knowledge can't understand.

This is used in a "file walker" function, where a binary file is loaded in memory then parsed to store its content in variables.
Some section of this files are skipped and this is how it's done:

file_walker += (size+3)&~0x3; 

"file_walker" is used to store the memory offset of the next chunk to read.

"size" is the size of the chunk size.

What I can't get is this part of the operation: "&~0x3". "&" and "~" are "NOT" and "AND" bitwise operators aren't they? How does this operation translates in layman terms?

While debugging, I can see that, if size = 3664, file_walker is incremented by 3664:

file_walker+=(3664+3)&~0x3;

"&~0x3" seem to be substracting 3 from the total, so then why add 3 if you remove it right-away?

If anyone could shed some light on the use of &~ in "arithmetic" operations I would greatly appreciated.

Thanks guys!

##### Share on other sites
They are AND and NOT, correct. But it doesn't subtract three, it clear the two lowest bits. Described in terms of arithmetics, and more specifically subtraction, it subtract either 0, 1, 2 or 3, so that the two lowest bits become zero. In other words, it rounds the number down to the nearest multiple of 4.

Together with adding 3, it effectively rounds up to the nearest multiple of 4.

Note, though, that this bit trickery is only valid for rounding to powers of two. Rounding up to any power of two N in general, you add (N-1) and mask with &~(N-1).

##### Share on other sites

They are AND and NOT, correct. But it doesn't subtract three, it clear the two lowest bits. Described in terms of arithmetics, and more specifically subtraction, it subtract either 0, 1, 2 or 3, so that the two lowest bits become zero. In other words, it rounds the number down to the nearest multiple of 4.

Together with adding 3, it effectively rounds up to the nearest multiple of 4.

Note, though, that this bit trickery is only valid for rounding to powers of two. Rounding up to any power of two N in general, you add (N-1) and mask with &~(N-1).

Got it! Thank you very much!

• ### Game Developer Survey

We are looking for qualified game developers to participate in a 10-minute online survey. Qualified participants will be offered a \$15 incentive for your time and insights. Click here to start!

• 15
• 21
• 21
• 11
• 9
×

## Important Information

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!