Classroom practice: Arithmetic types
Gábor Horváth / Zsolt Kohári · 2020.10.09.
Working with characters, character coding. Number systems, conversion between number systems.
Let us write a program that reads a text from the standard input, converts it to lowercase letters (or capital letters) and prints it to the screen! Characters other than letters should be left unchanged. First solve the task by converting the cases manually, then solve it by using the related built-in functions! Use the same algorithm to modify strings coming from the user. Use scan() to read, printf() to write the modified string!
hex | bin | dec |
---|---|---|
0 | 0000 | 0 |
1 | 0001 | 1 |
2 | 0010 | 2 |
… | … | … |
E | 1110 | 14 |
F | 1111 | 15 |
Let us convert the following base-2 (binary) numbers to base-10 (decimal) numbers, on paper: 1011, 1101, 10000, 10101! Let us convert the following decimal numbers to binary numbers: 13, 27, 35.
Let us convert the following base-16 (hexadecimal) numbers to binary numbers: 0x1F, 0xFCE2, 0xABBA, 0xC0FFEE! Let us convert the following binary numbers to hexadecimal: 11111111, 1011100, 101, 10101! During the conversions do not use the decimal system as an intermediate step!
Hint
24=16, thus every hexadecimal digit can be represented by exactly 4 binary digits, as shown on the right. Therefore, the hexadecimal value of binary number 101011 is 0x2B, since the lower 4 bits (starting from the right) are 1011 (=0xB), and for the upper bits we have 10=0x2.
Let us do the calculations below in the binary system, without converting the terms to decimal!
1001 + 101 ─────
1111 +1000 ─────
1111 + 1 ─────
Let us write a program that prints a number in a given number system!
Let us solve the task both with and without arrays!
Hints
- Dividing the number by the base of the number system and taking the remainder gives us the last digit. For instance, 1234 % 10 = 4, the number ends with digit 4.
- If we take the result of the division instead, we get the remaining part of the number (to be printed out): 1234 / 10 = 123.
- Doing these steps iteratively we get all the numeric digits to print, with one flaw: in a reverse order!
Let us modify the program to get it work with number systems with base greater than 10! (For instance, with base 16 numbers). The digit 10 and the values greater than that are denoted by letters in this case. In base 16 system the 0…15 digits are: 012…89ABCDEF.