CSCI-1190: Beginning C Programming For Engineers: Lecture 6: Number Systems
CSCI-1190: Beginning C Programming For Engineers: Lecture 6: Number Systems
x 0 0 1 0 0 1 0 1 37
x<<1 74
x<<2 148
x<<3 40
x>>1 18
x>>2 9
x>>3 4
From Binary to Decimal
• Input as a string: 0100101
• From characters to digits:
'0' → 0, '1' → 1
• Calculate:
0*26+1*25+0*24+0*23+1*22+0*21+1*20
= 0+32+0+0+4+0+1=37
From Decimal to Binary
• Input as an integer: 37
• Repeat:
– x&27 → 0 → 0
– x&26 → 0 → 0
– x&25 → 32 → 1
– x&24 → 0 → 0
– x&23 → 0 → 0
– x&22 → 4 → 1
– x&21 → 0 → 0
– x&20 → 1 → 1
In-Class Exercise 6-1
• Write a program that reads an integer from
the keyboard, then prints out its binary
representation.
– Assume the input integer is always smaller than
216=65536
– Use the shift operator to generate the sequence
of 215,214,213,…,21,20
Octal Numbers
• Base: 8
• Digits: {0,1,2,3,4,5,6,7}
• Examples:
127 = 1*82+2*81+7*80 = 87
• Octal integer constants are numbers with a leading
zero
017 /* 1*8+7=15 */
0234 /* 2*64+3*8+4=156 */
019 /* error */
Hexadecimal Numbers
• Base: 16
• Digits: {0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F}
• Examples:
– A2F = A*162+2*161+F*160
= 10*162+2*161+15*160 = 2607
• Hex integer constants are numbers with a leading 0x
0x11 /* 1*16+1=17 */
0xA0 /* 10*16+0=160 */
0xAB /* 10*16+11=171 */
Bit Pattern Conversions
Octal Numbers Hexadecimal Numbers
0 000 0 0000 8 1000
1 001 1 0001 9 1001
2 010 2 0010 A 1010
3 011 3 0011 B 1011
4 100 4 0100 C 1100
5 101 5 0101 D 1101
6 110 6 0110 E 1110
7 111 7 0111 F 1111
• No binary constants in C
• Octal and hexadecimal constants are convenient
– 101 1001 1011 1101 1111 = 0x59BDF
From Hex to Dec
• Input as a string: 59BDF
• From characters to digits:
/* a is the character */
a is '0'-'9': n=a-'0';
a is 'A'-'F': n=a-'A'+10;
• From digits to the number
59BDF
=5*164+9*163+11*162+14*161+15*160
From Dec to Hex
• Input as an integer: 44444
• Repeat:
– 44444/163=10 remainder 3484 10 → ‘A’
– 3484/162=13 remainder 156 13 → ‘D’
– 156/161=9 remainder 12: 9→ ‘9’
– 12/160=12 remainder 0: 12 → ‘C’
• This algorithm also works for octal numbers and
binary numbers
In-Class Exercise 6-2
• Write a program that reads an integer from
the keyboard, then prints out its
hexadecimal representation.
– Assume the input integer is smaller than
164=65536, so we start from 163=4096