summaryrefslogtreecommitdiff
path: root/CSAPP/chap2/shift_big.c
diff options
context:
space:
mode:
authorCarlos Maiolino <[email protected]>2025-07-10 22:55:07 +0200
committerCarlos Maiolino <[email protected]>2025-07-10 22:56:55 +0200
commitd98f46ce647846b0aa30b2e16a30fd4e152a1bf5 (patch)
tree267474fcc77cf20b428f6f4c7f768ca09f4cfe0e /CSAPP/chap2/shift_big.c
parent869e68986aa8f69af6e7842260a68d1e5c6f796f (diff)
Add new code
Signed-off-by: Carlos Maiolino <[email protected]>
Diffstat (limited to 'CSAPP/chap2/shift_big.c')
-rw-r--r--CSAPP/chap2/shift_big.c40
1 files changed, 40 insertions, 0 deletions
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 <stdio.h>
+
+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;
+}