/* shift.c * For use in CSE351 Lec 5 on Integers * * Demonstrates the different effects of right and left shifting * in combination with signed and unsigned "8-bit" data. */ #include int main() { // IMPORTANT: printf assumes most integral types are 32-bits. printf("\n"); printf("** Left Shift (<<) **\n"); unsigned char x = 0x19; unsigned char L1 = x<<2; unsigned char L2 = x<<3; unsigned char L3 = x<<4; // Show the shifted bit pattern by outputting in hex (%.2X formats the // output as >=2 capital hex digits) printf("* Hex: x = 0x%.2X, L1 = 0x%.2X, L2 = 0x%.2X, L3 = 0x%.2X\n", x, L1, L2, L3); // Leave the type alone to show their interpretation as unsigned values. printf("* Unsigned: x = %4u, L1 = %4u, L2 = %4u, L3 = %4u\n", x, L1, L2, L3); // Explicitly cast to a signed char, to show how these bit patterns are // interpreted as signed values (%4 just means to pad to 4 characters in // length) printf("* Signed: x = %4d, L1 = %4d, L2 = %4d, L3 = %4d\n", (char)x, (char)L1, (char)L2, (char)L3); printf("\n*********************\n"); printf("\n"); printf("** Right Shift (>>) **\n"); // Recall that right-shifting an UNsigned value performs a logical // shift (ie, fills with 0s), and that right shifting a SIGNED value // performs an arithmetic shift (ie, fill with the sign bit). unsigned char xu = 0xF0; char xs = 0xF0; unsigned char R1u = xu>>3; char R1s = xs>>3; unsigned char R2u = xu>>5; char R2s = xs>>5; // As before, we show the shifted bit pattern (first column) followed by // the values' interpretation as an unsigned integer. This limits us to // only showing the logical right shift (since you can't have a logical // shift of a signed value). printf("Logical:\n"); printf("* Hex: xu = 0x%.2X, R1 = 0x%.2X, R2 = 0x%.2X\n", xu, R1u, R2u); printf("* Unsigned: xu = %4u, R1 = %4u, R2 = %4u\n", xu, R1u, R2u); printf("\n"); printf("Arithmetic:\n"); printf("* Hex: xu = 0x%.2X, R1 = 0x%.2X, R2 = 0x%.2X\n", // cast to unsigned to prevent printf's unwanted sign extension (unsigned char)xs, (unsigned char)R1s, (unsigned char)R2s); printf("* Signed: xu = %4d, R1 = %4d, R2 = %4d\n", xs, R1s, R2s); // main() function in C is supposed to return an int; this return value // is used by the OS to determine the program's status. return 0; }