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/casting.c | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 CSAPP/chap2/casting.c (limited to 'CSAPP/chap2/casting.c') 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 + +/* 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; +} -- cgit v1.2.3