summaryrefslogtreecommitdiff
path: root/CSAPP/chap2/casting.c
diff options
context:
space:
mode:
Diffstat (limited to 'CSAPP/chap2/casting.c')
-rw-r--r--CSAPP/chap2/casting.c36
1 files changed, 36 insertions, 0 deletions
diff --git a/CSAPP/chap2/casting.c b/CSAPP/chap2/casting.c
new file mode 100644
index 0000000..5089802
--- /dev/null
+++ b/CSAPP/chap2/casting.c
@@ -0,0 +1,36 @@
+/*
+ * Shows how the conversion between signed and unsigned are made.
+ * Most machines follow the rule that the underlying bit pattern doesn't change.
+ * Let's see
+ */
+
+#include <stdio.h>
+
+/* 10101010
+ * integers are usually considered signed by default unless we append
+ * the suffix U to the number*/
+#define NUM 0xAA
+int x = -1;
+unsigned u = 2147483648;
+
+int main(void) {
+
+ unsigned char a = NUM;
+ printf("Original unsigned number - HEX: 0x%.2X %d\n", a, a);
+ /* there is no formatter to print a single byte integer, printing it
+ * with %d would result in a cast to integer, printing 4 bytes, so let's
+ * print it only in HEX
+ */
+
+ printf("Signed conversion number - HEX: 0x%.2X DEC: %d\n", (char)a, (signed char)a);
+
+ printf("x = %d - x = %u - 0x%X\n", x, x, x);
+ printf("u = %d - u = %u - 0x%X\n", u, u, u);
+
+ /*
+ * When one of the operands in an equation is unsigned, C will cast the
+ * another operand to unsigned too before making the operation
+ */
+ printf("%X\n", -2147483647);
+ return 0;
+}