// String to Integer and Integer to String Conversion

import java.util.Scanner;

public class Convert {

    public static void main(String[] args) {

        Scanner keyboard = new Scanner(System.in);

        // Main loop
        while (true) {

            System.out.print("Enter a number: ");
            String input = keyboard.next();

            // Check for done
            if (input.toLowerCase().equals("exit")) break;
            
            // Convert to number
            int number = parseNumber(input);
            
            // Display number
            System.out.println("Decimal value = " + toString(number, 10));
            System.out.println("Hexadecimal value = " + toString(number, 16));
            System.out.println("Binary value = " + toString(number, 2));
            System.out.println();
        }
    }

    static int parseNumber(String string) {
        
        int number = 0;
        int base = 10;
        int digit;
        
        // Determine base of number
        switch (string.substring(0,2)) {
            case "0b": base =  2; break;
            case "0x": base = 16; break;
        }

        // Remove prefix
        if (base != 10) string = string.substring(2);

        // Make lowercase
        string = string.toLowerCase();

        // Extract number from string
        for (int i = 0; i < string.length(); i++) {

            // Convert char to digit
            char c = string.charAt(i);
            if (Character.isDigit(c))
                digit = c - '0';
            else
                digit = c - 'A' + 10;
            
            // Shift number and add digit 
            number *= base;
            number += digit;
        }
        
        return number;
    }
    
    static String toString(int number, int base) {

        String string = "";
        int digit;
        char c;
        
        while (number > 0) {
            
            // Extract digit and shift
            digit = number % base;
            number = number / base; 
            
            // Convert digit to character
            if (digit < 10)
                c = (char) (digit + '0');
            else
                c = (char) (digit + 'A' - 10);
            
            // Add character to string
            string = c + string;
        }
        
        // Add prefix
        if (base == 2) string = "0b" + string;
        else if (base == 16) string = "0x" + string;
        
        return string;
    }
}

© 2013 CS160 Colorado State University. All Rights Reserved.