Sometimes it is required to flip the bytes of an integer. For example some image formats stores the chunks in ABGR format, so you have to flip them for use in OpenGL or Direct3D.

This could be achieved fast and simple with bit operations and byte shifts:

#include <iostream>

using namespace std;

unsigned int reverseBytes(unsigned int value)
{ 
    return 
        (value & 0xFF) << 24 | 
        (value >> 8 & 0xFF) << 16 | 
        (value >> 16 & 0xFF) << 8 | 
        (value >> 24 & 0xFF);
}

int main (int argc, char * const argv[]) {
    unsigned int a = 0xFFAA9933;
    a = reverseBytes(a);
    printf("%Xn", a);  //output: 0x3399AAFF
    return 0;
}

If you remember my blog post “Swapping two variables” and you’ll think a little bit further, you can adapt it to come to the following solution:

#include <iostream>

using namespace std;

void reverseBytes(unsigned int &a) {
    char* c = reinterpret_cast<char*>(&a);

    // swap first and last byte
    c[0] ^= c[3];
    c[3] ^= c[0];
    c[0] ^= c[3];
    
    // swap second and third byte
    c[1] ^= c[2];
    c[2] ^= c[1];
    c[1] ^= c[2];
}

int main (int argc, char * const argv[]) {
    unsigned int a = 0xFFAA9933;
    reverseBytes(a);
    printf("%Xn", a);  //output: 0x3399AAFF
    return 0;
}

While this one is quite nice to know, I prefer the first solution, because it’s a little bit easier to read, it results in fewer instructions after compilation and you don’t have to use a reinterpret_cast.

  1. Paulmichael (2011-01-15 08:57)

    Enjoying these “Hack of the Day” articles, even though I don’t yet understand a lot of them – Computer Science student here! :)

  2. joe (2011-01-15 09:04)

    If you have any questions don’t hesitate to ask and I’ll try to answer them and/or update my posts. I’ll try to explain them better in the future!

  3. gdev (2011-01-19 21:48)

    This should be faster :)return ((value&0x000000ff)<<24) | ((value&0x0000ff00)<<8) | ((value&0x00ff0000)>>8) | ((value&0xff000000)>>24);

  4. joe (2011-01-19 23:07)

    @gdev: thank you! (i tried to fix your post, so the code looks right. code doesn’t work very well in the comments – i think i’ll have to look out for a code-comments-plugin for wordpress.)

Add your comment now