Java: convert binary string to hex string [duplicate]
Asked Answered
M

3

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

Microclimatology answered 21/10, 2013 at 11:57 Comment(3)
can't you just append the missing 0's by hand?African
Use String.format method to append the String with 0'sMallorca
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.Blatt
P
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)) ;
}
Pepin answered 21/10, 2013 at 12:25 Comment(0)
G
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.

Gunboat answered 21/10, 2013 at 12:15 Comment(0)
L
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");
}
Lesley answered 21/10, 2013 at 12:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.