Is there a better way to reverse an array of bytes in memory?

xian picture xian · Feb 25, 2009 · Viewed 18.2k times · Source
typedef unsigned char Byte;

...

void ReverseBytes( void *start, int size )
{
    Byte *buffer = (Byte *)(start);

    for( int i = 0; i < size / 2; i++ ) {
        std::swap( buffer[i], buffer[size - i - 1] );
    }
}

What this method does right now is it reverses bytes in memory. What I would like to know is, is there a better way to get the same effect? The whole "size / 2" part seems like a bad thing, but I'm not sure.

EDIT: I just realized how bad the title I put for this question was, so I [hopefully] fixed it.

Answer

kmkaplan picture kmkaplan · Feb 25, 2009

The standard library has a std::reverse function:

#include <algorithm>
void ReverseBytes( void *start, int size )
{
    char *istart = start, *iend = istart + size;
    std::reverse(istart, iend);
}