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.

1. Small letters, capital letters

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!

2. Number systems

hexbindec
000000
100011
200102
E111014
F111115

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
─────

3. Reading numbers in a given number system

Let us read a number from the user, in the number system specified by the user!

First get it work with the decimal system, then generalize to arbitrary base!

Which number system to use?
16
Enter the number!
fce2
In decimal system the number is: 64738

4. Printing numbers in a given number system

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.