From d98f46ce647846b0aa30b2e16a30fd4e152a1bf5 Mon Sep 17 00:00:00 2001 From: Carlos Maiolino Date: Thu, 10 Jul 2025 22:55:07 +0200 Subject: Add new code Signed-off-by: Carlos Maiolino --- CSAPP/chap2/shift_big.c | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 CSAPP/chap2/shift_big.c (limited to 'CSAPP/chap2/shift_big.c') diff --git a/CSAPP/chap2/shift_big.c b/CSAPP/chap2/shift_big.c new file mode 100644 index 0000000..8a54c56 --- /dev/null +++ b/CSAPP/chap2/shift_big.c @@ -0,0 +1,40 @@ +/* + * What happens when the shift value is bigger than the amount of bits in the + * variable? + * + * Some machines will only use the lower log2 w bits of the shift amount when + * shifting a 2-bit falue. + * + * For example, shifting a 8-bit value by 10, would make the machine shift the + * value for only 2 (a k mod w). + * + * This is not a rule though. Let's test it. + * + * Looks like linux GCC on 64bit will always shift the exactly number, and crop + * only the exactly number of bits for the data type representation. + * + * For signed integers, if the shift is done right in the printf, gcc will use a + * convert it to a signed 32-bits for the conversion. + * + * Try change the x in printf on line 32, to use "a << 10" directly. + */ +#include + +int main(void) +{ + /* 10101001 */ + char x, a = 0xA9; + unsigned char y, b = 0xA9; + + + printf("Signed Original value: 0x%.2x\n", a); + x = a << 10; + printf("Signed left shift by 10: 0x%.2x\n\n", x); + + + printf("Unsigned Original value: 0x%.2x\n", b); + y = b << 10; + printf("Unsigned left shift by 10: 0x%.2x\n", y); + + return 0; +} -- cgit v1.2.3