Search code examples
javaradix

base conversions - decimal to octal


In the code below I'm trying to convert 15 base 10 into it's value in base 8 which is 17. But instead the program below gives me 13 and not 17. The method baseEight receives 15 as a string then it is my understanding that Integer.parseInt baesEight takes the value 15 and converts it into a base 8 value which should be 17. But it's not. I'm not sure what it's wrong.

import acm.program.*;

public class BaseCoversion  extends ConsoleProgran{
  public void run(){

    int a = 15; 
    String a = Integer.toString(a);
    println(a);
  }

  private int baseEight(String s) {
    return Integer.parseInt(s , 8 );
  }

} 

Solution

  • To get the octal representation of a number, you need to either pass the radix to Integer.toString(int, int) method, or use Integer.toOctalString(int) method:

    int a = 15; 
    String s = Integer.toOctalString(a);
    System.out.println(Integer.parseInt(s));
    

    Integer.parseInt(String, int) parses the string using the given radix. You don't want that. The output you are asking for is just the representation of the number in base 8.