Search code examples
javahexbiginteger

How to convert BigInteger value to Hex in Java


I am making a Java program. I have a BigInteger number and I need to convert it to Hexadecimal. I tried the following code:

String dec = null;
System.out.println("Enter the value in Dec: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
dec = br.readLine();  
BigInteger toHex=new BigInteger(dec,16);
String s=toHex.toString(16);
System.out.println("The value in Hex is: "+ s);

However, this does not give me the correct value after conversion. I am not sure how I can achieve the desired output.

Any help is welcome.


Solution

  • You should change

    BigInteger toHex=new BigInteger(dec,16);
    

    to

    BigInteger toHex=new BigInteger(dec,10);
                                         ^
    

    Currently you ask the user for a dec-value, and then interpret the input as a hex-value. (That's why the output is identical to the input.)