Skip to main content
gamedev.net
🔒 Locked

Bit Operations.

Started by mrmrcoleman Jan 21, 2004 at 9:13 AM 1 replies 250+ views
Original Post
mrmrcoleman
mrmrcoleman
Bonjourno... I have found the following code in an DirectX9 SDK sample and I need to be able to understand it to move on.
LONG m_lVidPitch;   // Video Pitch

m_lVidPitch  = (m_lVidWidth * 3 + 3) & ~(3); // Forcing RGB24

This code sets the pitch of a surface, although I dont understand the syntax. What does the ''& ~(3)'' do? Also does anyone know of any tutorials where I can learn all this bit manipulation stuff for myself? Thank you in advance. Mark Coleman
circlesoft
circlesoft
The ~ operator is kind of unusual - it is refered to as the One's Complement Operator. For a good explanation, you may want to look up '~' in the MSDN library.

The & operator performs Bitwise-Ands. It compares each bit of its first operand to the corresponding bit of its second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.

[edited by - circlesoft on January 21, 2004 10:44:36 AM]
Agony
Agony
About.com - Bit Operations. About.com has plenty of good stuff for C++, at least in my experience.

As for that specific code, ~(3) is taking the bitwise NOT of 3. 3 in binary (assuming 8 bits, although it's probably 32) is 00000011. The not just turns all 0s into 1s and vice versa, so ~(3) = 11111100. If it is 32 bits, then it'll just be a whole lot more 1s in front, and then two 0s. The & does a bitwise AND of the two values. A bitwise AND compares bits in the first value to bits in the second value, and if they're both 1, then the result bit is 1, if either one, or both are 0, then the result bit is zero. So taking any number and ANDing it with 1111...11111100 is basically making sure that the last two bits are 00, and everything else remains the same. Making the last two bits 00 makes the resulting number evenly divisible by 4.

So the purpose I would suppose of that code would be to get pitch (which is number of bytes) equal to 3 times the width (3 bytes per pixel). But they also want to make sure pitch is divisible by 4, so that it will fit into memory well, by being aligned to 32 bits. So they add an extra 3 to the m_lVidWidth as extra padding, and then reduce the number by the right amount to make sure it is divisible by four. That's the & ~(3) part.

Hope the About.com stuff helps, if my explanation was a bit poor, which wouldn't surprise me.

[Edit - clarified that the link wasn't just to About.com's homepage]

[edited by - Agony on January 21, 2004 10:54:46 AM]
"We should have a great fewer disputes in the world if words were taken for what they are, the signs of our ideas nly, and not for things themselves." - John Locke o

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.