Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert BigInteger value to Hex in Java

Tags:

java

I have a BigInteger number and I need to convert it to Hexadecimal. I tried the following:

    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);

But this does not give me the correct value after conversion. Can anybody help.

like image 685
Jury A Avatar asked Aug 11 '12 22:08

Jury A


People also ask

Can we convert BigInteger to integer in Java?

intValue() converts this BigInteger to an int. This conversion is analogous to a narrowing primitive conversion from long to int. If this BigInteger is too big to fit in an int, only the low-order 32 bits are returned.

How do I change BigInteger to string?

BigInteger. toString() method returns the decimal String representation of this BigInteger. This method is useful to convert BigInteger to String. One can apply all string operation on BigInteger after applying toString() on BigInteger.


1 Answers

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.)

like image 74
aioobe Avatar answered Oct 22 '22 00:10

aioobe