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

Nunzio Meli
  • 89
  • 2
  • 2
  • 8

3 Answers3

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)) ;
}
Rune Aamodt
  • 2,427
  • 1
  • 22
  • 27
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.

Stanislav Mamontov
  • 1,574
  • 13
  • 21
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");
}
Bohemian
  • 365,064
  • 84
  • 522
  • 658