Last active
April 24, 2024 12:01
-
-
Save jdupuy/d8cb371b8341e5f38e9dcc604f71b486 to your computer and use it in GitHub Desktop.
Reversing bits of a word
This file contains 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
uint8_t BitReverse(uint8_t x) | |
{ | |
x = ((x & 0x0F) << 4) | ((x & 0xF0) >> 4); | |
x = ((x & 0x33) << 2) | ((x & 0xCC) >> 2); | |
x = ((x & 0x55) << 1) | ((x & 0xAA) >> 1); | |
return x; | |
} | |
uint16_t BitReverse(uint16_t x) | |
{ | |
x = ((x & 0x00FF) << 8) | ((x & 0xFF00) >> 8); | |
x = ((x & 0x0F0F) << 4) | ((x & 0xF0F0) >> 4); | |
x = ((x & 0x3333) << 2) | ((x & 0xCCCC) >> 2); | |
x = ((x & 0x5555) << 1) | ((x & 0xAAAA) >> 1); | |
return x; | |
} | |
uint32_t BitReverse(uint32_t x) | |
{ | |
x = ( x << 16) | ( x >> 16); | |
x = ((x & 0x00FF00FF) << 8) | ((x & 0xFF00FF00) >> 8); | |
x = ((x & 0x0F0F0F0F) << 4) | ((x & 0xF0F0F0F0) >> 4); | |
x = ((x & 0x33333333) << 2) | ((x & 0xCCCCCCCC) >> 2); | |
x = ((x & 0x55555555) << 1) | ((x & 0xAAAAAAAA) >> 1); | |
return x; | |
} | |
uint64_t BitReverse(uint64_t x) | |
{ | |
x = ( x << 32) | ( x >> 32); | |
x = ((x & 0x0000FFFF0000FFFF) << 16) | ((x & 0xFFFF0000FFFF0000) >> 16); | |
x = ((x & 0x00FF00FF00FF00FF) << 8) | ((x & 0xFF00FF00FF00FF00) >> 8); | |
x = ((x & 0x0F0F0F0F0F0F0F0F) << 4) | ((x & 0xF0F0F0F0F0F0F0F0) >> 4); | |
x = ((x & 0x3333333333333333) << 2) | ((x & 0xCCCCCCCCCCCCCCCC) >> 2); | |
x = ((x & 0x5555555555555555) << 1) | ((x & 0xAAAAAAAAAAAAAAAA) >> 1); | |
return x; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment