summaryrefslogtreecommitdiff
path: root/CSAPP/chap2/shifts.c
blob: 836476d75e8aeeedad94edf56a13ba39c40f12ad (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
37
38
39
/*
 * Shift operations
 *
 * Right shifts might use either arithmetic shifts or logical shifts.
 *
 * This small piece of code should identify which one is used
 */

#include <stdio.h>

int main(void)
{
	/* Using char so we care for a single byte only */
	char x, a;
	unsigned char y, b;
	/* bin 10101001 */
	a = b = 0xA9;

	printf("Original signed variable: 0x%.2x\n", a);

	/*
	 * Signed data variables are right shifted using Arithmetic shift. i.e.
	 * left bits are filled with a copy of the most significant bit of the
	 * original value
	 */
	x = a >> 3;
	printf("Signed right shift by 3: 0x%.2x\n\n", x);

	printf("Original unsigned variable: 0x%.2x\n", b);
	/*
	 * Unsigned data variables are right shifted logically. i.e. left bits
	 * are just filled with zeros
	 */
	y = b >> 3;
	printf("Unsigned right shift by 3: 0x%.2x\n", y);
	return 0;
}