Changes

Jump to: navigation, search

Computer Architecture

194 bytes added, 11:09, 26 September 2019
Sub-word and Unaligned Access
== Sub-word and Unaligned Access ==
Most processors use a [[Word|word]] size that is multiple of width of some common data types. However, it is often necessary to access data which is a fraction of this size -- for example, a system with a 32-bit [[Word#Hardware Word|hardware word size]] that is running applications which use UTF-8 character encoding may often need to read or write single [[Word#Byte|bytes]] of data. A byte-sized read will cause the CPU to perform a 32-bit read, followed by [[Bitwise Operations|masking and shifting operations]] to extract the desired byte from the 32-bit word. A single-byte write operation will cause the CPU to read the existing word, extract the unaffected bits within that word (with similar to an [[Bitwise Operations#AND|AND]]operation), merg in the new value (similar to an [[Bitwise Operations#OR|OR]] in the new valueoperation), and then write the word back to memory.
Unaligned memory access causes similar issues. For example, to read a 32-bit value from the byte address 0x2, most 32-bit CPUs will read a 32-bit value starting at byte address 0x0 and perform an [[Bitwise Operations|AND]] to extract highest 16 bits, then a shift to move those bits to the lowest 16 bit positions. The CPU will then read a 32-bit value starting at byte address 0x4, perform the equivalent of an AND to extract the lowest 16 bits, shift those bits to the highest 16 bit positions, and then OR the high 16 bits and the low 16 bits together into a single 32 bit value. These operations are usually hardware-optimized to occur much faster than the equivalent software operations. (Writing an unaligned 32-bit value is even worsethan reading it!)
Obviously, unaligned access is far slower than aligned access, and should be avoided whenever possible. However, aligning all storage may result in increased memory usage (e.g., aligning 24-bit pixel values on 32-bit boundaries), and some data such as compressed data streams or network packets will almost always contain unaligned data.

Navigation menu