Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a large binary string to hexadecimal

Tags:

java

I have a binary string:

1010010111100101100010101010011011010001111100000010101000000000010000000111110111100"

How can I convert it to a hex string?

I tried with the wrapper classes Long and Integer, but it didn’t work for me, throwing a NumberFormatException.

like image 227
user2451783 Avatar asked Jun 04 '13 12:06

user2451783


1 Answers

You need to use BigInteger for this - the number is too big to fit in a primitive value. The biggest number that can be stored in a long is 9223372036854775807, whereas the equivalent value in decimal of this binary string is much bigger, 25069592479040759763832764. That's why you're getting the NumberFormatException.

So with BigInteger:

String s = "1010010111100101100010101010011011010001111100000010101000000000010000000111110111100";
BigInteger b = new BigInteger(s, 2);
System.out.println(b.toString(16));

...which gives:

14bcb154da3e0540080fbc
like image 55
Michael Berry Avatar answered Nov 15 '22 01:11

Michael Berry