Saturday, November 21, 2009

Convert Base5 number to Decimal

The following is the code to convert a base 5 integer into decimal number. This program, can also be used to convert a number in other number systems to decimal number system. The conversion is performed by the valueOf() method of the Integer class.
public class Base5Demo {
public Integer convertBase5( String number ){
Integer x;

x = Integer.valueOf(number, 5);
return x;
}

public static void main(String args[]){
String num = "230";
Base5Demo base5 = new Base5Demo();

System.out.format("%d",base5.convertBase5(num));
}
}


In the above program, intially the number is stored in string 's'. 's' is in the number system represented by the integer 5, i.e, base 5 number system. This integer is called radix.

The output of the above program is: 65(230 in base5 system).

Binary to Decimal
The above program can be tried for binary number conversion also. A program for this purpose would be as follows:
public class convertBinaryDemo {
public Integer convertBinary( String number ){
Integer x;

x = Integer.valueOf(number, 2);
return x;
}

public static void main(String args[]){
String num = "0110";
convertBinaryDemo bin = new convertBinaryDemo();

System.out.format("%d",bin.convertBinary(num));
}
}


Output: 6

No comments:

Post a Comment