Checking if an address is page-aligned

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
tobbebia
Posts: 17
Joined: Fri Feb 19, 2010 1:49 pm
Location: Sweden

Checking if an address is page-aligned

Post 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
My GitHub account: http://github.com/tobbebia
evoex
Member
Member
Posts: 103
Joined: Tue Dec 13, 2011 4:11 pm

Re: Checking if an address is page-aligned

Post 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.
tobbebia
Posts: 17
Joined: Fri Feb 19, 2010 1:49 pm
Location: Sweden

Re: Checking if an address is page-aligned

Post by tobbebia »

Thanks for your kind and helpful reply!

I will take your advice and use adress AND 0xFFF.
My GitHub account: http://github.com/tobbebia
Post Reply