Byte Swapping in C


Some times you need to swap bytes. Sometimes you don’t. But right now we do. Well, we don’t but if we were implementing some sorting functions we’d need a good swap function. Sorting typically doesn’t move pointers around, instead it moves the bytes pointed to by the pointer.

Generic Swap

We only want to have one swap function and not one for every single possible type. We’ll use void pointers and a width (number of bytes the type occupies) to make a generic swap function.

void swap(void *a, void *b, size_t width)
	char   *v1 = (char *)a;
	char   *v2 = (char *)b;
	char    tmp;
	size_t  i;

	for (i=0; i<width; i++) {
		tmp   = v1[i];
		v1[i] = v2[i];
		v2[i] = tmp;

First, the void pointer will be changed into a `char` pointer because a `char` is always 1 byte. We know the width so we know how many bytes from the pointer the element occupies. Thus, all we need to do is loop the number of bytes to the size given by `width` and swap the values.

It might seem like this shouldn’t work but lets think about this a bit. An integer, for example, occupies 4 bytes in memory. These 4 bytes taken together represent an integer. And the value of the integer is split across 4 bytes. If we copy the value of every byte to another location we will still have the same integer value. Just at a different location.