summaryrefslogtreecommitdiff
path: root/CSAPP/chap2/casting.c
blob: 5089802c6046518f5d032a1bcf57a37791c818e2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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;
}