Skip to content

Instantly share code, notes, and snippets.

@jniemann66
Created August 7, 2019 11:06
Show Gist options
  • Save jniemann66/9d41dc729cc5b28995b16b54a6b63949 to your computer and use it in GitHub Desktop.
Save jniemann66/9d41dc729cc5b28995b16b54a6b63949 to your computer and use it in GitHub Desktop.
Byte swapping with built-in functions
#include <cstddef>
#include <cstdint>
// gcc >= 4.8.1
// clang >= 3.5
uint16_t a1 = 0x0102;
uint32_t a2 = 0x01020304;
uint64_t a3 = 0x0102030405060708ull;
auto b1 = __builtin_bswap16(a1);
auto b2 = __builtin_bswap32(a2);
auto b3 = __builtin_bswap64(a3);
// MSVC
#include
#include <stdlib.h>
_byteswap_ushort(v);
_byteswap_ulong(v);
_byteswap_uint64(v);
// Naive: (note: anonymous structs are not officially part of C++, although they seem to work on all? compilers)
// gcc -O2 is smart enough to convert all this to bswap instruction !
uint16_t swapEndian(uint16_t x) {
union {
struct {
uint8_t a;
uint8_t b;
};
uint16_t n;
} y, z;
y.n = x;
z.a = y.b;
z.b = y.a;
return z.n;
}
uint32_t swapEndian(uint32_t x) {
union {
struct {
uint8_t a;
uint8_t b;
uint8_t c;
uint8_t d;
};
uint32_t n;
} y, z;
y.n = x;
z.a = y.d;
z.b = y.c;
z.c = y.b;
z.d = y.a;
return z.n;
}
uint64_t swapEndian(uint64_t x) {
union {
struct {
uint8_t a;
uint8_t b;
uint8_t c;
uint8_t d;
uint8_t e;
uint8_t f;
uint8_t g;
uint8_t h;
};
uint64_t n;
} y, z;
y.n = x;
z.a = y.h;
z.b = y.g;
z.c = y.f;
z.d = y.e;
z.e = y.d;
z.f = y.c;
z.g = y.b;
z.h = y.a;
return z.n;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment