7.4 Exercises

7.4.1 Converting decimal numbers into base N

  1. Create a conversion function dec2base(x, base) that converts a decimal number x into a positional number of different base (with \(2 \leq\) base \(\leq 10\)). Thus, the dec2base() function provides a complement to base2dec() from the i2ds package:
library(i2ds)
base2dec(1011, base = 2)
#> [1] 11
dec2base(11,   base = 2)
#> [1] 1011
  1. Use your dec2base() function to compute the following conversions:
dec2base(100, base =  2)
dec2base(100, base =  3)
dec2base(100, base =  5)
dec2base(100, base =  9)
dec2base(100, base = 10)
  1. Create a brief simulation that samples \(N = 20\) random decimal numbers \(x_i\) and base values \(b_i\) and shows that

base2dec(dec2base(\(x_i,\ b_i\)),\(b_i\)) ==\(x_i\)

(i.e., converting a decimal number into a number of base \(b_i\) and back into a decimal number yields the original decimal number).

Solution

Table 7.1: Convert decimal numbers into some base, and back into a decimal number.
dec_num into_base num_base num_base_as_dec same
8748 9 13000 8748 TRUE
331 2 101001011 331 TRUE
9162 7 35466 9162 TRUE
9845 9 14448 9845 TRUE
1319 4 110213 1319 TRUE
6747 4 1221123 6747 TRUE
9974 2 10011011110110 9974 TRUE
3971 6 30215 3971 TRUE
1052 7 3032 1052 TRUE
1767 5 24032 1767 TRUE
2649 5 41044 2649 TRUE
1747 3 2101201 1747 TRUE
4810 6 34134 4810 TRUE
3903 7 14244 3903 TRUE
8733 7 34314 8733 TRUE
1178 9 1548 1178 TRUE
1631 2 11001011111 1631 TRUE
9475 8 22403 9475 TRUE
3318 2 110011110110 3318 TRUE
207 10 207 207 TRUE
519 5 4034 519 TRUE
7685 10 7685 7685 TRUE
3133 8 6075 3133 TRUE
5418 8 12452 5418 TRUE
8808 5 240213 8808 TRUE

7.4.2 Exercise