I just saw this in some code I have to work on:
I just don't understand what it tries to do. What would be the value chunkLength if len is equal to 10 for example?Code:chunkLength = (len+3)&~3
PS: Both, chunkLength and len are integers.
I just saw this in some code I have to work on:
I just don't understand what it tries to do. What would be the value chunkLength if len is equal to 10 for example?Code:chunkLength = (len+3)&~3
PS: Both, chunkLength and len are integers.
Let's assume 16-bit integers to make this more terse. It would add 3 to 10 first. 13 decimal is 00000000 00001101 in binary. The ~3 takes 3 in binary and reverses all the bits so it results in 11111111 11111100
Then you AND those together:
00000000 00001101
&
11111111 11111100
=
00000000 00001100
So chunkLength would end up being 12 decimal.
Last edited by itsme86; 04-07-2005 at 07:31 AM.
If you understand what you're doing, you're not learning anything.
This truly is a diamond piece of code .. NOT
Basically, it's adding the value 3 to the length variable, and then "turning off" the last 2 bits of the number (~ being bitwise NOT).
Examples (using 5 bits.. on the machine it's probably 32):
3 (decimal) = 00011 (binary)
~3 = 11100 (binary)
if len = 8 (decimal) = 01000 (binary)
len + 3 = 11 (decimal) = 01011 (binary)
(len+3)&~3 = 01000 (binary) = 8 (decimal)
if len = 9 (decimal) = 01001 (binary)
len + 3 = 12 (decimal) = 01100 (binary)
(len+3)&~3 = 01100 (binary) = 12 (decimal)
if len = 10 (decimal) = 01010 (binary)
len + 3 = 13 (decimal) = 01101 (binary)
(len+3)&~3 = 01100 (binary) = 12 (decimal)
if len = 11 (decimal) = 01011 (binary)
len + 3 = 14 (decimal) = 01110 (binary)
(len+3)&~3 = 01100 (binary) = 12 (decimal)
if len = 12 (decimal) = 01100 (binary)
len + 3 = 15 (decimal) = 01111 (binary)
(len+3)&~3 = 01100 (binary) = 12 (decimal)
if len = 13 (decimal) = 01101 (binary)
len + 3 = 16 (decimal) = 10000 (binary)
(len+3)&~3 = 10000 (binary) = 16 (decimal)
Basically, it looks like it's trying to find the minimum size required to contain a given value or something similar, given a chunk size of 4?!
Don't know if that'll help, but hey, it might clear something up
Good luck!
[Edit: d*mn, ya beat me to it ]
Thanks a lot to both of you, it was a great help. I think the reason for this kind of code (there is more code with similar "wierd" operations) is that it works in a little endian kind of way, that's my guess. Anyway, all that code is legacy code.