Skip to content

Instantly share code, notes, and snippets.

@rojaster
Created February 13, 2022 19:31
Show Gist options
  • Save rojaster/e790a28f0d9a35006e88aab6e55656c1 to your computer and use it in GitHub Desktop.
Save rojaster/e790a28f0d9a35006e88aab6e55656c1 to your computer and use it in GitHub Desktop.
Unsigned int bytes reverse
// all the cases in the end gonna be reduced by compiler to the latest variant
// so even, knowing builtin function could save you time, but if you case
// recognizable by the compiler, don't worry to use your way of doing things.
#include <iostream>
#include <stdint.h>
using namespace std;
// 4 bytes: 3 2 1 0 -> 0 1 2 3
unsigned reverse_bytes(unsigned num) {
return ((num & 0xFF000000) >> 24)
| ((num & 0xFF0000) >> 8)
| ((num & 0xFF00) << 8 )
| ((num & 0xFF) << 24);
}
unsigned reverse_bytes1(unsigned num) {
uint8_t *n1, *n2;
unsigned reversed;
n1 = (uint8_t *) &num;
n2 = (uint8_t *) &reversed;
n2[0] = n1[3];
n2[1] = n1[2];
n2[2] = n1[1];
n2[3] = n1[0];
return reversed;
}
unsigned reverse_bytes2(unsigned num) {
unsigned reversed;
union {
unsigned n;
uint8_t nb[4];
} repr;
repr.n = num;
reversed = (repr.nb[0] << 24) | (repr.nb[1] << 16) | (repr.nb[2] << 8) | repr.nb[3];
return reversed;
}
unsigned reverse_bytes3(unsigned num) {
return __builtin_bswap32(num);
}
int main()
{
unsigned num = 12341235;
/* The compiler inserts an implicit float upcast. */
cout << "Before " << hex << num << endl;
cout << "After " << hex << reverse_bytes(num) << endl;
cout << "Before " << hex << num << endl;
cout << "After " << hex << reverse_bytes1(num) << endl;
cout << "Before " << hex << num << endl;
cout << "After " << hex << reverse_bytes2(num) << endl;
cout << "Before " << hex << num << endl;
cout << "After " << hex << reverse_bytes3(num) << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment