THINK FIRST·CODE LATER

← All labs

Number bases, recursively

Problem

Write RecursiveBases with four recursive methods (no loops, no Integer.toBinaryString or parseInt with a base):

  • decToBin(int n) and decToHex(int n) return a String;
  • binToDec(String bits) and hexToDec(String hex) return an int.

Ideas: the binary form of n is the binary form of n / 2 followed by the bit n % 2; the value of a bit string is twice the value of all its bits but the last, plus the last bit.

main reads pairs dec 13, bin 1101 or hex 1F until the end of the input. For the input

dec 13
dec 255
dec 0
bin 1101
hex 1F
hex ff
dec 4096

the program prints

13 = 1101 in binary = D in hexadecimal
255 = 11111111 in binary = FF in hexadecimal
0 = 0 in binary = 0 in hexadecimal
1101 in binary = 13
1F in hexadecimal = 31
ff in hexadecimal = 255
4096 = 1000000000000 in binary = 1000 in hexadecimal

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

l17-7-data-1.txt

dec 13
dec 255
dec 0
bin 1101
hex 1F
hex ff
dec 4096
What your program must print for l17-7-data-1.txt
13 = 1101 in binary = D in hexadecimal
255 = 11111111 in binary = FF in hexadecimal
0 = 0 in binary = 0 in hexadecimal
1101 in binary = 13
1F in hexadecimal = 31
ff in hexadecimal = 255
4096 = 1000000000000 in binary = 1000 in hexadecimal

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < l17-7-data-1.txt

Windows PowerShell does not understand <:

Get-Content l17-7-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.