CS 0447 – Lab 1: Base Converter

In class, we talked about a variety of ways to write a particular numerical value. In your first lab, you are going to write a Java program that converts a number in a specified base into other bases.

Operation

The program will take two command line arguments. The first will be a number in binary, decimal, or hexadecimal. The second parameter will indicate the base of the number (2, 10, or 16). Your job is to take that number and then display it in all three representations using the following format:

$> java BaseConverter 111010101 2

Dec: 469

Bin: 0000000111010101

Hex: 01d5

Requirements and Hints

·         The maximum input will be a 16-bit binary string. That means a 4-digit hex string.

·         You do not need to handle negative numbers.

·         All hex letters will be lowercase (‘a’, ‘b’, etc.).

·         You may assume valid input.

·         Print out leading zeros as in the example above.

·         You may use Integer.parseInt(String), but not any of Java’s built in functions to do base conversion. That includes but is not limited to Integer.parseInt(String, int radix), Integer.toHexString(), Integer.toBinaryString(), Character.digit(), Character.forDigit(), or printf(). You’re writing this to learn how to do the calculations algorithmically, not how to call Java library functions.

·         That said, those functions can help you verify your code is working correctly.

·         Your best bet will be to convert the input to a decimal int (not a short!) from whatever base it is in (you can use Integer.parseInt() if it is in base 10 already). Then use that int value to convert to binary and hexadecimal.

Due Date and Submission

This lab is due during your scheduled recitation on May 29, 2012 or May 31, 2012.

We will formalize submission policies for this class by then, but please bring your code to recitation.

Just for fun

Add unary (base 1) to your program. You’ll quickly appreciate why it is rarely used.