Page 1 of 1

Checking if an address is page-aligned

Posted: Sat Jan 28, 2012 1:29 pm
by tobbebia
Hey,
I'm following JamesM's tutorial and I'm reading the part about paging. To check if an address is NOT page-aligned he uses this code:

Code: Select all

if(placement_address & 0xFFFFF000) {
 // NOT aligned
}
I don't understand how AND can be used to do this. For the statement to be true the result of (placement_address & 0xFFFFF000) should be 1, right?

So first I tried doing the AND operation on a value that is page-aligned:

8192 AND 0xFFFFF000

000000000000000000010000000000000
AND
100000000000000000000000000000000
=
000000000000000000000000000000000

Then on a value that is not page-aligned:

000000000000000000010000000000001
AND
100000000000000000000000000000000
=
000000000000000000000000000000000

Which gave the same result, so how can that code be used to determine if its page-aligned?

Can MOD be used?
E.g.

Code: Select all

if(placement_address % 0x1000) {
 // NOT aligned
}
It feels like there is something I don't understand, please help me!

Link to the tutorial: http://www.jamesmolloy.co.uk/tutorial_h ... aging.html

Re: Checking if an address is page-aligned

Posted: Sat Jan 28, 2012 1:37 pm
by evoex
I think you're right, it seems like a bug in the tutorial. Ouch. It seems like this code will waste one entire page if aligned memory is requested, but the placement address is already aligned. It wouldn't break anything, but it could potentially waste some memory.

Yes, you can use modulo. You CAN also use a bitwise and, but for the opposite of what is actually in the code:

Code: Select all

if(address & 0xFFF) {
  // NOT aligned.
}
The bitwise and will be faster, but your compiler will probably optimize it to that anyway, even when using modulo. So either is fine.

Re: Checking if an address is page-aligned

Posted: Sat Jan 28, 2012 3:44 pm
by tobbebia
Thanks for your kind and helpful reply!

I will take your advice and use adress AND 0xFFF.