0

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.

SatyaTNV
  • 4,137
  • 3
  • 15
  • 31
Pratyush
  • 68
  • 8

3 Answers3

2

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).
Community
  • 1
  • 1
InfectedPacket
  • 264
  • 2
  • 8
  • This is a good approach, but you have to handle the case where the input string isn't a multiple of 4. – ajb Oct 10 '15 at 05:05
  • Agreed. You could still use the length of the string, modulo 4 and use the result as the number of "0" to prefix the string (if it's not a stream). However `BigInteger` is much more elegant and faster. – InfectedPacket Oct 10 '15 at 05:13
1

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");
Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
0
   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
Rajan Kali
  • 12,627
  • 3
  • 25
  • 37