Java:将二进制字符串转换为十六进制字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19493873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: convert binary string to hex string
提问by Nunzio Meli
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:
该方法返回:123456789ABCDEF,但我想返回:
00000123456789ABCDEF
00000123456789ABCDEF
采纳答案by Rune Aamodt
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):
而不是Long.toHexString
我会Long.parseLong
用来解析值,然后String.format
输出具有所需宽度的值(在您的示例中为 21):
public static String binaryToHex(String bin) {
return String.format("%21X", Long.parseLong(bin,2)) ;
}
回答by Stanislav Mamontov
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.
我使用 String.format() 用空格左填充字符串,然后调用 replace() 用零替换它。
回答by Bohemian
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}", "");
}