Last active
March 21, 2021 10:01
-
-
Save kugland/bb43bf6f81a5ab461c721abd626ca11f to your computer and use it in GitHub Desktop.
Bit reflect for uint64_t hand-optimized for size for AVR processors. https://godbolt.org/z/qjn8rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <inttypes.h> | |
typedef union { | |
uint64_t u64; | |
uint8_t u8[8]; | |
} uint64_union; | |
__attribute__((optimize("Os"))) // Avoid loop unrolling. | |
void reflect_u64(uint64_t* value) | |
{ | |
// Let's operate on memory instead of using registers. | |
uint64_union *orig = (uint64_union *) value; | |
// Reflect the bits of each byte of the 64-bit value. | |
for (int i = 0; i < 8; i++) { | |
uint8_t src = orig->u8[i]; | |
uint8_t tmp = 0; | |
for (int j = 0; j < 8; j++) { | |
tmp <<= 1; | |
tmp |= src & 1; | |
src >>= 1; | |
} | |
orig->u8[i] = tmp; | |
} | |
// Reflect the bytes (refl[0] = orig[7]; refl[1] = orig[6] &c) | |
for (int i = 0; i < 4; i++) { | |
uint8_t tmp = orig->u8[i]; | |
orig->u8[i] = orig->u8[7 - i]; | |
orig->u8[7 - i] = tmp; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment