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

This topic is 2590 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!

1. 1
2. 2
3. 3
Rutin
23
4. 4
5. 5
khawk
14

• 9
• 11
• 11
• 23
• 12
• Forum Statistics

• Total Topics
633653
• Total Posts
3013165
×