octal and hexadecimal in java code example
Example 1: octal to hexadecimal in java
import java.util.Scanner;
public class OctalToHexadecimal
{
public static void main(String[] args)
{
String strOctalNumber, strHexNumber;
Scanner sc = new Scanner(System.in);
System.out.print("Please enter octal number: ");
strOctalNumber = sc.nextLine();
int decimalNumber = Integer.parseInt(strOctalNumber, 8);
strHexNumber = Integer.toHexString(decimalNumber);
System.out.print("Hexadecimal value of " + strOctalNumber + " is: \n");
System.out.print(strHexNumber);
sc.close();
}
}
Example 2: hexadecimal to octal in java
import java.util.Scanner;
public class HexadecimalToOctal
{
public static void main(String[] args)
{
int decimalNumber, a = 1, b;
int[] octalNumber = new int[100];
Scanner sc = new Scanner(System.in);
System.out.print("Please enter a hexadecimal number: ");
String strHexNumber = sc.nextLine();
decimalNumber = hexToDecimal(strHexNumber);
while(decimalNumber != 0)
{
octalNumber[a++] = decimalNumber % 8;
decimalNumber = decimalNumber / 8;
}
System.out.print("Octal number is: ");
for(b = a - 1; b > 0; b--)
{
System.out.print(octalNumber[b]);
}
System.out.print("\n");
sc.close();
}
public static int hexToDecimal(String str)
{
String strDigits = "0123456789ABCDEF";
str = str.toUpperCase();
int value = 0;
for(int a = 0; a < str.length(); a++)
{
char ch = str.charAt(a);
int deci = strDigits.indexOf(ch);
value = 16 * value + deci;
}
return value;
}
}