For pleasure, it follows in a recursive solution that works for any width of digits.
#include <limits.h> unsigned ReverseHex(unsigned x, unsigned DigitWidth) { if (DigitWidth <= 1) { return x; } unsigned SideDigitWidth = DigitWidth / 2; unsigned SideBitWidth = SideDigitWidth * 4; unsigned CenterAndRightDigitWidth = DigitWidth - SideDigitWidth; unsigned CenterAndRightBitWidth = CenterAndRightDigitWidth * 4; unsigned CenterAndRight = x & ((1u << CenterAndRightBitWidth) - 1); unsigned Right = x & ((1u << SideBitWidth) - 1); unsigned Center = CenterAndRight - Right; return ReverseHex(x >> CenterAndRightBitWidth, SideDigitWidth) + Center + (ReverseHex(Right, SideDigitWidth) << CenterAndRightBitWidth); } int main(void) { printf("%X\n", ReverseHex(0x1234, 4)); printf("%X\n", ReverseHex(0x12345, 5)); printf("%X\n", ReverseHex(0x1234567, 7)); printf("%X\n", ReverseHex(0x12345678, 8)); return 0; }
Exit
4321 54321 7654321 87654321
source share