Octal to decimal in java

Hey guys!! Welcome to flower brackets blog. Today we are going to learn octal to decimal in java.

octal to decimal java

Integer class provides a method Integer.parseInt(String s, int radix) which converts binary, hexadecimal and octal number to decimal number.

Also read – convert decimal to octal java program

The parameters in the above method namely “String s” and “int radix” indicates

  • String s – binary, hexadecimal and octal number,
  • int radix – in what base the first argument is represented.

Also it’s size is less than 32-bits. However, size greater than 32-bits will throw an unchecked runtime java.lang.NumberFormatException. Here’s java program,

public class OctalToDecimalDemo 
{
   public static void main(String[] args) 
   { 
      String strOctal = "141"; 
      // converting octal to decimal using Integer.parseInt 
      int decimal = Integer.parseInt(strOctal, 8); 
      System.out.println(decimal);
   }
}

Output:

97


Meanwhile we can execute using method. Here’s the code,

public class OctalCode 
{
   public static int octalToDecimal(int octalNumber)
   { 
      int decimal = 0; 
      int num = 0; 
      while(true)
      { 
         if(octalNumber == 0)
         { 
            break; 
         }
         else
         { 
            int temp = octalNumber % 10; 
            decimal += temp * Math.pow(8, num); 
            octalNumber = octalNumber / 10; 
            num++; 
         } 
      } 
      return decimal; 
   }

   public static void main(String[] args) 
   { 
      System.out.println("141 octal is : " + octalToDecimal(141)); 
      System.out.println("230 octal is : " + octalToDecimal(230)); 
      System.out.println("100 octal is : " + octalToDecimal(100));
   }
}

Output:

141 octal is : 97
230 octal is : 152
100 octal is : 64

Related Posts