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)) ;
}