22

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.

Dinux
  • 644
  • 1
  • 6
  • 19
Jury A
  • 19,192
  • 24
  • 69
  • 93

5 Answers5

20

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

aioobe
  • 413,195
  • 112
  • 811
  • 826
  • need to improve my typing speed – Dungeon Hunter Aug 11 '12 at 22:26
  • Ok. But what is the difference between writing: `String s=toHex.toString(16);` and `String s=toHex.toString();` ?? – Jury A Aug 11 '12 at 22:27
  • `toString()` will return a base-10 representation of the number, while `toString(16)` will return a base-16 representation of the number. – aioobe Aug 11 '12 at 22:28
  • What should I use because both of them gives me the correct output. So I don't understand. If I entered input 15, I get f in both ways. – Jury A Aug 11 '12 at 22:32
10
String hexValue = "FFF";
    System.out.println("HexaDecimal Value :"+hexValue);
    BigInteger bigint = new BigInteger(hexValue ,16);
    System.out.println("Big Int Value :"+bigint);
    BigInteger s = new BigInteger("4");
    bigint = bigint.add(s);
    System.out.println("After Addition :"+bigint);
    String hexNewValue = bigint.toString(16);
    System.out.println("HexaDecimal Value after Addition :"+hexNewValue);
Surjeet Katwal
  • 116
  • 1
  • 2
4

I think I see the problem:

BigInteger toHex=new BigInteger(dec,16);

You are converting the number you type to an integer using base 16. Try using 10 here.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
2

use

 BigInteger toHex=new BigInteger(dec,10);
Dungeon Hunter
  • 19,827
  • 13
  • 59
  • 82
0

there is a same questions: i have a BigInteger value like this:

 BigDecimal price = BigDecimal.valueOf(1151234).movePointRight(16);

and i want convert price to hex, i just write this code. then it output as i expect:

    System.out.println("0x" + price.toBigInteger().toString(16));
    //expect 0x27015cfcb0230820000
    //output 0x27015cfcb0230820000
curits
  • 1
  • 1