开发者

Function for converting octal to hexadecimal in Java

Is there a function I can use to convert octal to hexadec开发者_如何学Cimal in java?


There's no single method, but you can easily do it via two steps:

  • parse your String containing the octal value to an int (or a long, depending on expected range)
  • Format that int/long to a hexadecimal String.

Those two steps can be done using Integer.parseInt(String, int) and Integer.toString(int, int) respectively. Be sure to use the two-argument versions and pass in 8 and 16 for octal and hexadecimal respectively.


This all assumes that your number, before and after, will be stored in a String (since it makes no sense to talk about base for an int/Integer):

Integer.toHexString(Integer.parseInt(someOctalString, 8));


String input = "1234";
String hex = Long.toHexString(Long.parseLong(input,8));


String octalNo="037";
System.out.println(Long.toHexString(Long.parseLong(octalNo,8)));


/**
 * This method takes octal input and convert it to Decimal
 * 
 * @param octalInput
 * @return  converted decimal value of the octal input  
 */
public static int ConvertOctalToDec( String octalInput )
{
    int a;
    int counter = 0;
    double product = 0;
    for ( int index = octalInput.length() ; index > 0 ; index -- )
    {
        a = Character.getNumericValue( octalInput.charAt( index - 1 ) );
        product = product + ( a * Math.pow( 8 , counter ) );
        counter ++ ;
    }
    return ( int ) product;
}

/**
 * This methods takes octal number as input and then calls
 * ConvertOctalToDec to convert octal to decimal number then converts it
 * to Hex
 * 
 * @param octalInput
 * @return Converted Hex value of octal input 
 */
public static String convertOctalToHex( String octalInput )
{
    int decimal = ConvertOctalToDec( octalInput );
    String hex = "";
    while ( decimal != 0 )
    {
        int hexValue = decimal % 16;
        hex = convertHexToChar( hexValue ) + hex;
        decimal = decimal / 16;
    }
    return hex;
}


I would do something like this

String oth=new BigInteger("37777777401",8).toString(16); //this is -255 to hex
System.out.println("octal to hex "+ oth);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜