3

I need to convert the binary string to a hex string but i have a problem. I converted the binary string to a hex string by this method:

public static String binaryToHex(String bin){
   return Long.toHexString(Long.parseLong(bin,2));
}

it's ok! but I lose the zeros to the left of the string. Ex:

the method return this: 123456789ABCDEF, but i want returned this:

00000123456789ABCDEF

3
  • can't you just append the missing 0's by hand? Commented Oct 21, 2013 at 11:58
  • 3
    Use String.format method to append the String with 0's Commented Oct 21, 2013 at 11:59
  • The reason why you loose them is because leading zero's in a Long have no value. You'll either have to change the way you process your conversion, or you will have to add them again by yourself. The String.format that @RohitJain suggested has my preference as well. Commented Oct 21, 2013 at 12:10

3 Answers 3

8

Instead of Long.toHexString I would use Long.parseLong to parse the value and then String.format to output the value with the desired width (21 in your example):


public static String binaryToHex(String bin) {
   return String.format("%21X", Long.parseLong(bin,2)) ;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Not very elegant, but works

public static String binaryToHex(String bin) {
    String hex = Long.toHexString(Long.parseLong(bin, 2));
    return String.format("%" + (int)(Math.ceil(bin.length() / 4.0)) + "s", hex).replace(' ', '0');
}

I've used String.format() to left pad string with whitespaces then called replace() to replace it with zeros.

Comments

0

Just add the zeros manually. Here's one way:

public static String binaryToHex(String bin){
    return ("0000000000000000" + Long.toHexString(Long.parseLong(bin, 2)).replaceAll(".*.{16}", "$1");
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.