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
For instance, in a 32-bit architecture, the data may be aligned if the data is stored in four consecutive bytes and the first byte lies on a 4-byte boundary. Data alignment is the aligning of elements according to their natural alignment.
When the database server passes the data type to a UDR, it aligns opaque-type data on a specified byte boundary. Alignment requirements depend on the C definition of the opaque data type and on the system (hardware and compiler) on which the opaque data type is compiled.
4k memory segments start at a hex address ending with 000. So all the addresses that end with 000 start on a 4 k boundary. However, addresses that end with 0000, 2000, 4000, 6000, 8000, a000, c000, or e000 also start on an 8k boundary. This is because hex 1000 is 4k or 2^12.
The alignment of the access refers to the address being a multiple of the transfer size. For example, an aligned 32 bit access will have the bottom 4 bits of the address as 0x0, 0x4, 0x8 and 0xC assuming the memory is byte addressed. An unaligned address is then an address that isn't a multiple of the transfer size.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With