CS 2731 Computer Organization II
|
The Java program below does fairly general number base conversions. It doesn't handle bases bigger than 10, though that would be fairly easy to include.
// ConvertBase.java: convert an int n to base b public class ConvertBase { private static char ch; // char location to hold next public static String convertToBase(int n, int b) { String s = new String(); int r; while (n != 0) { r = n%b; ch = (char)(r + '0'); s = ch + s; n = n/b; } return s; } // main function to try out Base class public static void main (String[] args) { int n; // number to convert to base b int b; // base for number conversions while(true) { System.out.print("Number to convert ----->"); n = GetNext.getNextInt(); if (n == 0) break; System.out.print("Base for conversion --->"); b = GetNext.getNextInt(); String conv = new String(); conv = ConvertBase.convertToBase(n, b); System.out.println(n + " to base " + b + " = " + conv); } } // end of main }
// GetNext.java: fetch the next char or int from standard input import java.io.*; public class GetNext { // in: reader for reading input data private static Reader in = new InputStreamReader(System.in); // ch: holds the next character read private static char ch; public static char getNextChar() { try { ch = (char)in.read(); } catch (Exception exception) { System.out.println("Error reading character"); ch = ' '; } return ch; } public static int getNextInt() { int num; // the number to convert int sign = 1; // gives sign of answer ch = getNextChar(); // skip over initial blanks and newlines while (ch == ' ' || ch == '\n') ch = getNextChar(); // check for + or - sign if (ch == '+') ch = getNextChar(); if (ch == '-') { sign = -1; ch = getNextChar(); } // read digits, construct input integer; // (same as the method "Integer.parseInt()" ) num = 0; while (Character.isDigit(ch)) { num = num*10 + (ch - '0'); ch = getNextChar(); } return sign * num; } }
% javac GetNext.java % javac ConvertBase.java % java ConvertBase Number to convert ----->153 Base for conversion --->8 153 to base 8 = 231 Number to convert ----->153 Base for conversion --->2 153 to base 2 = 10011001 Number to convert ----->1000000000 Base for conversion --->2 1000000000 to base 2 = 111011100110101100101000000000 Number to convert ----->1000 Base for conversion --->8 1000 to base 8 = 1750 Number to convert ----->0