/* * reverseNybbles.c * * Created on: Apr 7, 2010 * Author: William D McQuain */ #include #include #include uint32_t reverseNybbles(uint32_t Original); int main(int argc, char** argv) { uint32_t value = 0x12345678; uint32_t reversed = reverseNybbles(value); // The statements below use special formatting macros from inttypes.h in // order to print uint32_t values. The usual string syntax is due to the // way C macros work. printf("Original: %" PRIx32 "\n", value); printf("Reversed: %" PRIx32 "\n", reversed); return 0; } /* * reverseNybbles() * Pre: Original is a 32-bit value, say MNOPQRST (as nybbles) * Returns: 32-bit value consisting of reversed nybbles from Original * e.g., TSRQPONM * * Exposition: * Given a 32-bit value MNOPQRST, we can obtain the low nybble by anding it with * an appropriate bit-mask: * * MNOPQRST & 0000000F --> 0000000T since x&1 == x and x&0 == 0 * (and F == 1111 in binary) * * Shifting 4 bits to the right removes the old low nybble and allows us to then * mask out the new low nybble (formerly the next-to-low nybble): * * MNOPQRST >> 4 --> ?MNOPQRS so masking now would yield 0000000S * * Shifting and adding will concatenate nybbles to form a new value; say we have * * Reversed == 00000000 * * Then: (00000000 << 4) + 0000000T == 0000000T * (0000000T << 4) + 0000000S == 000000TS * ... * * Note: the right-shift operator (>>) may shift in 0's or 1's at the high end; * see King:510 for a discussion of the issues; in this application we do * not need to care what bits are shifted in. */ uint32_t reverseNybbles(uint32_t Original) { uint32_t loMask = 0x0000000F; // Mask for "extracting" the low nybble: // 0000 0000 0000 0000 0000 0000 0000 1111 uint32_t Reversed = 0; // holds reversed form uint32_t currentNybble; // holds current nybble from Original for (int nybble = 0; nybble < 8; nybble++) { // 8 nybbles, so... currentNybble = Original & loMask; // get the current low nybble Reversed = (Reversed << 4) + currentNybble; // shift and add to build reversed form Original = Original >> 4; // shift out the old low nybble } return Reversed; }