5

What is the method that you can use to convert between bases in Java? It is something like IntegerToBase (int, base), but I cannot remember.

user1755178
  • 255
  • 1
  • 4
  • 9

3 Answers3

14

Literally speaking, integer values are not converted from one base to another. Thanks to von Neumann, one of the pioneers of computing, who thought the idea of trying to use base 10 arithmetic on binary circuitry made little sense, integers are stored in binary format and we are not trying to change that :-) What we are talking about is converting them to strings representing them in some base (other that base 10 which is the default) and converting strings to integers in bases other than (the default) base 10. The necessary tools are static methods of the Integer class.

  • Java provides the Integer.toString(int i, int radix) conversion function which takes an integer and a radix (the base) and returns that integer's string representation in that base.

    String hexRepr = Integer.toString(255, 16)  // returns "FF"
    
  • To go the other way around, i.e. from a string representing a number in a different base there is Integer.parseInt(String s, int radix)

    int myNum = Integer.parseInt("FF", 16)  // returns 255
    
  • To convert a number represented as a base radix1 string to a base radix2 string representation the two methods just mentioned have to be combined as the following examples shows:

    int radix1 = 16;  // The input will be parsed assuming base 16 representation
    int radix2 = 4;   // The result will be output using a base 4 representation
    String input = "FF"; // which in base 16 represents the number 255 
    String converted = Integer.toString(Integer.parseInt(radix1Representation, radix1),radix2);  /// returns "3333"  which in base 4 is the number 255
    

More details can be found in the API documentation. I have included some of it here, to ensure readers also see the things they need to be careful with when using these methods.


public static String toString(int i, int radix)

This method returns a string representation of the first argument in the radix specified by the second argument.

If the radix is smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX, then the radix 10 is used instead.

If the first argument is negative, the first element of the result is the ASCII minus character '-' ('\u002D'). If the first argument is not negative, no sign character appears in the result.

The remaining characters of the result represent the magnitude of the first argument. If the magnitude is zero, it is represented by a single zero character '0' ('\u0030'); otherwise, the first character of the representation of the magnitude will not be the zero character. The following ASCII characters are used as digits:

0123456789abcdefghijklmnopqrstuvwxyz 

These are '\u0030' through '\u0039' and '\u0061' through '\u007A'. If radix is N, then the first N of these characters are used as radix-N digits in the order shown. Thus, the digits for hexadecimal (radix 16) are 0123456789abcdef. If uppercase letters are desired, the String.toUpperCase() method may be called on the result:

Integer.toString(n, 16).toUpperCase() 

Source: http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toString%28int,%20int%29


public static int parseInt(String s, int radix) throws NumberFormatException

This method parses the string argument as a signed integer in the radix specified by the second argument. The characters in the string must all be digits of the specified radix (as determined by whether Character.digit(char, int) returns a nonnegative value), except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value. The resulting integer value is returned.

An exception of type NumberFormatException is thrown if any of the following situations occurs:

  • The first argument is null or is a string of length zero.

  • The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX.

  • Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign '-' ('\u002D') or plus sign '+' ('\u002B') provided that the string is longer than length 1.

  • The value represented by the string is not a value of type int.

Examples:

parseInt("0", 10)           // returns 0
parseInt("473", 10)         // returns 473
parseInt("+42", 10)         // returns 42
parseInt("-0", 10)          // returns 0
parseInt("-FF", 16)         // returns -255
parseInt("1100110", 2)      // returns 102
parseInt("2147483647", 10)  // returns 2147483647
parseInt("-2147483648", 10) // returns -2147483648
parseInt("2147483648", 10)  // throws NumberFormatException
parseInt("99", 8)           // throws NumberFormatException
parseInt("Kona", 10)        // throws NumberFormatException
parseInt("Kona", 27)        // returns 411787

Source: http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt%28java.lang.String,%20int%29

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
Miltos Kokkonidis
  • 3,888
  • 20
  • 14
3

You can use Integer.parseInt("101", 2) for example, it will give you 5 (correspond decimal number).

Returns an Integer object holding the value extracted from the specified String when parsed with the radix given by the second argument. The first argument is interpreted as representing a signed integer in the radix specified by the second argument, exactly as if the arguments were given to the parseInt(java.lang.String, int) method. The result is an Integer object that represents the integer value specified by the string. In other words, this method returns an Integer object equal to the value of: (source)

new Integer(Integer.parseInt(s, radix))

From the same source, you also have:

public static String toString(int i,int radix)

Returns a string representation of the first argument in the radix specified by the second argument.

So if you want to convert from binary to decimal:

Integer.parseInt(binary_number_in_string, 2);

if you want from decimal to binary:

System.out.println(Integer.toString(2,2));

To convert from another base to decimal and vise versa you just have to change the radix parameter.


Note that the class Integer have already some default conversation methods, such as:

public static String toBinaryString(int i) 

Returns a string representation of the integer argument as an unsigned integer in base 2 (source).

public static String toHexString(int i) 

Returns a string representation of the integer argument as an unsigned integer in base 16 (source).

public static String toOctalString(int i) 

Returns a string representation of the integer argument as an unsigned integer in base 8 (source).

As you can see from the return type of the above methods, it is not the integer that are being convert between base. The methods are returning the String representation in a give base of the integer pass as a argument.

dreamcrash
  • 47,137
  • 25
  • 94
  • 117
3

The Integer class offers two utility methods which offer this functionality, although strings are the medium of conversion:

Note that Integer internally stores values in decimal form (base 10).

For example, to convert 01000 (octal) to 512 (decimal) and back, you can do the following:

String octal = "01000";
int i = Integer.parseInt(octal, 8);
String decimal = Integer.toString(i, 10);
System.out.println(decimal); // prints 512
cHao
  • 84,970
  • 20
  • 145
  • 172
FThompson
  • 28,352
  • 13
  • 60
  • 93
  • I didnt check BUT basic arithmetic tells me that octal 100 can not be equal to decimal 512, more like 64. – mazaneicha Dec 01 '12 at 00:17
  • @mazaneicha You are talking about string representation of numbers, not about numbers. – Sulthan Dec 01 '12 at 00:18
  • @Sulthan String "0100" interpreted as octal number will yield decimal number 64. If you add one "0" to the end -- "01000" -- it will be 512 decimal. Just a simple typo in the response that I tried to point.. – mazaneicha Dec 01 '12 at 00:48
  • @mazaneicha Nice catch, cHao appears to have edited it to have the correct octal/decimal values. – FThompson Dec 01 '12 at 00:51