// CS 350, Illinois Inst Tech, J. Sasaki // Lecture 8, Spring 2012 // // Bit shifting examples in C // #include // Instructions: Compile with LENGTH of 0, 1, or 2 to run the // examples on characters, short integers, or regular integers. // #define LENGTH 0 #if LENGTH == 2 #define TYPE int #define TYPENAME "int" #define MAX_POS 0x7fffffff #define MAX_NEG 0x80000000 #define NEG_ONE 0xffffffff // For printing: // %2d means >= 2 chars signed decimal (including possible '-' // sign), blank-filled // %#010x means leading 0x, zero-filled, >= 10 chars hex // %...X means upper case hex (A-F instead of a-f) // #define FORMAT1 "1 << %2d = %#010x = %d\n" #define FORMAT2 "%08x << %2d = %08x = %d\n" #define FORMAT3 "%08X >> %2d = %08X = %d\n" #elif LENGTH == 1 #define TYPE short int #define TYPENAME "short int" #define MAX_POS 0x7fff #define MAX_NEG 0x8000 #define NEG_ONE 0xffff // For printing: // %...h means the value is a short int // %...hh means the value is a char // #define FORMAT1 "1 << %2d = %#06hx = %d\n" #define FORMAT2 "%04hx << %2d = %04hx = %d\n" #define FORMAT3 "%04hX >> %2d = %04hX = %d\n" #elif LENGTH == 0 #define TYPE char #define TYPENAME "char" #define MAX_POS 0x7f #define MAX_NEG 0x80 #define NEG_ONE 0xff #define FORMAT1 "1 << %d = %#04hhx = %d\n" #define FORMAT2 "%02hhx << %d = %02hhx = %d\n" #define FORMAT3 "%02hhX >> %d = %02hhX = %d\n" #endif int main(void) { printf("Bit-shifting on %s values:\n\n", TYPENAME); TYPE value, n, power; // 1 << i is 1 shifted left i bits (equals 2 to the i power). // The loop runs a couple times more than the width (in bits) // of the type: sizeof( a type name ) = # bytes for that type. // int i; for (i = 0; i < sizeof(TYPE)*8+2; i++) { power = 1 << i; printf(FORMAT1, i, power, power); } printf("\n"); n = NEG_ONE; for (i = 0; i < sizeof(TYPE)*8+2; i++) { value = n << i; printf(FORMAT2, n, i, value, value); } printf("\n"); // n >> i = n shifted right i bits, either 0 or sign-bit filled. // (The standard leaves this choice up to the implementation.) // n = MAX_POS; for (i = 0; i < sizeof(TYPE)*8+2; i++) { value = n >> i; printf(FORMAT3, n, i, value, value); } printf("\n"); // Try shifting maximum negative value right // n = MAX_NEG; for (i = 0; i < sizeof(TYPE)*8+2; i++) { value = n >> i; printf(FORMAT3, n, i, value, value); } printf("\n"); return 0; }