/* Name: ex20-7.c Purpose: Practice with "bit fiddling" Author: The rotate functions given here were provided by W.W. Norton & Co.; the main() function written by Bill Slough */ #include #define HIGH_BIT (~(~0U >> 1)) #define LOW_BIT 1 #define NBITS 32 /* rotate the quantity i by n bit positions to the left */ unsigned int rotate_left(unsigned int i, int n) { while (n-- > 0) i = (i << 1) | (i & HIGH_BIT ? LOW_BIT : 0); return i; } /* rotate the quantity i by n bit positions to the right */ unsigned int rotate_right(unsigned int i, int n) { while (n-- > 0) i = (i >> 1) | (i & LOW_BIT ? HIGH_BIT : 0); return i; } int main(void) { /* a simple test driver/demo for the rotate functions */ unsigned int myValue = 0x12345678; int n; /* test the left rotations */ printf("Left rotations:\n"); for (n = 0; n <= NBITS; n++) printf("...by %2d positions: %8.8x\n", n, rotate_left(myValue, n)); /* test the right rotations */ printf("\nRight rotations:\n"); for (n = 0; n <= NBITS; n++) printf("...by %2d positions: %8.8x\n", n, rotate_right(myValue, n)); return 0; }