Advertisement
FatalSleep

Byte Alignment Explanation

May 7th, 2014
329
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. When dealing with buffers you have to handle byte alignment. Byte alignment can be pretty tricky, I just noticed that my old version of byte alignment was terrible as it did not include dynamic sized data, e.g. strings.
  2.  
  3. Byte alignment in short is fitting(padding) bytes in between each piece of data based on the amount of alignment of the buffer and the size of the data. You want to fit in the amount of bytes that would make the data fit to the amount of alignment of the buffer. Example Image of buffers using various alignments: http://i.imgur.com/4H5d1fm.png Red is 1 byte, green is 2 bytes, blue is 4 bytes.
  4.  
  5. After alignment if you "mod"(mod is %) the data, the amount of bytes + padding should equal 0. Here is how it works:
  6.  
  7. if ( String_Length % Alignment != 0 ) {
  8. Padding = Alignment - ( String_Length % Alignment );
  9. }
  10.  
  11. Padding is the total bytes to fit in between the current piece of data and the next piece of data to align the current piece of data to the alignment of the buffer.
  12.  
  13. So let's solve this using various alignments and data sizes:
  14. Alignment of 4, data size of 5 byte string:
  15. if ( 5 % 4 != 0 ), result 1, continue:
  16. Padding = 4 - ( 5 % 4 ), Padding = 3.
  17. Check: 5 + 3 = 8, 8 mod 4 = 0. Correct!
  18.  
  19. Alignment of 2 , data size of 8 byte int:
  20. if ( 8 % 2 != 0 ), result stop!
  21. The data is already aligned. So no padding is added.
  22.  
  23. That is how you do byte alignment for buffers!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement