Pratyush
Pratyush

Reputation: 68

How to convert a String consisting of Binary Number to Hexa Decimal no in Java?

My String is 010101010111111111101010101010101010111101010101010101010101 and it is large in size (more than 64 characters).

I cannot use Integer or Long class parse methods due to size limitation.

Expected Output would be 557FEAAAAF55555h.

Upvotes: 0

Views: 81

Answers (3)

Rajan Kali
Rajan Kali

Reputation: 12953

   public  String GetHex(String binary){
        String[] parts=binary.split("(?<=\\G.{4})");
        String output="";
        for(String s: parts)
        {
            output+=Integer.toHexString(Integer.parseInt(s, 2));
        }
    }

And Call it with your Binary String

 String binary="010101010111111111101010101010101010111101010101010101010101";
     String hexvalue=GetHex(binary); //557feaaaaf55555

Upvotes: 0

Erwin Bolwidt
Erwin Bolwidt

Reputation: 31269

Use BigInteger for this:

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

This shows:

557feaaaaf55555

Or to get your exact output:

System.out.println(value.toString(16).toUpperCase() + "h");

Upvotes: 1

InfectedPacket
InfectedPacket

Reputation: 274

I don't know your performance requirements, but it seems to me you could simply:

  1. Split your string into nibbles of 4 (see Splitting a string at every n-th character);
  2. Then convert each of them into an integer (see Converting String to Int in Java?);
  3. And finally and concatenate their hexadecimal value (see Java.lang.Integer.toHexString() Method).

Upvotes: 2

Related Questions