Amit Singh Tomar
Amit Singh Tomar

Reputation: 8610

How Do I check a Memory address is 32 bit aligned in C

My question has two parts.

First, as a newbie to this address space, I would like to know what is the meaning of memory alignment of an address. I Googled about it but wanted to ask this question here as well since I found answers here very useful.

The second part of my question is related to alignment and programming: how do I find if an address is 4 byte aligned or not ? Somewhere I read:

  if(address & 0x3) // for 32 bit register 

But I don't really know how this checks for a 4 byte alignment. Could anyone explain it in detail?

Edit: It would be great If someone can draw pictorial view on this subject.

Thanks

Upvotes: 24

Views: 54346

Answers (1)

lurker
lurker

Reputation: 58244

Sequential addresses refer to sequential bytes in memory.

An address that is "4-byte aligned" is a multiple of 4 bytes. In other words, the binary representation of the address ends in two zeros (00), since in binary, it's a multiple of the binary value of 4 (100b). The test for 4-byte aligned address is, therefore:

if ( (address & 0x3) == 0 )
{
    // The address is 4-byte aligned here
}

or simply

if ( !(address & 0x3) )
{
    // The address is 4-byte aligned here
}

The 0x3 is binary 11, or a mask of the lowest two bits of the address.

Alignment is important since some CPU operations are faster if the address of a data item is aligned. This is because CPUs are 32-bit or 64-bit word based. Small amounts of data (say 4 bytes, for example) fit nicely in a 32-bit word if it is 4-byte aligned. If it is not aligned, it can cross a 32-bit boundary and require additional memory fetches. Modern CPUs have other optimizations as well that improve performance for address aligned data.

Here's a sample article regarding the topic of alignment and speed.

Here are some some nice diagrams of alignment.

Upvotes: 41

Related Questions