Wednesday, September 2, 2009

Byte swizzling

So, we have all heard about little endian and big endian concepts. We all know that in a little endian system the least significant byte gets stored first, or at the lowest address. In a big endian system the most gets stored in first, or at the lowest address.

So what happens if you are trying to read data that has been stored in a big endian system?

Say you have 0xDEADBEEF stored like so:

Memory:
a => DE
a+1 => AD
a+2 => BE
a+3 => EF

if you have a 32 bit pointer address pointing to a+3 the value read will be 0XEFBEADDE. In order to make sense of the value you will need to swizzle it. In other words; you will need to change the order of bytes.

Here is code which will swizzle a 32 bit value:


#include <stdio.h>
#include <string.h>
#include <stdlib.h>


#define CODETOSWIZZLE 0XEFBEADDE
int main()
{

unsigned int swizzledCode = \
((CODETOSWIZZLE & 0x000000FF)<<24)\
+((CODETOSWIZZLE & 0x0000FF00)<<8)\
+((CODETOSWIZZLE & 0x00FF0000)>>8)\
+((CODETOSWIZZLE & 0xFF000000)>>24);

printf("Swizzled %x", swizzledCode);

getchar();
return 0;
}

No comments: