将十六进制字符串(hex)转换为二进制字符串
我找到了以下十六进制到二进制转换的方式:
I found the following way hex to binary conversion:
String binAddr = Integer.toBinaryString(Integer.parseInt(hexAddr, 16));
虽然这种方法适用于较小的十六进制数,但像下面这样的十六进制数
While this approach works for small hex numbers, a hex number such as the following
A14AA1DBDB818F9759
抛出 NumberFormatException.
因此,我编写了以下似乎可行的方法:
I therefore wrote the following method that seems to work:
private String hexToBin(String hex){
String bin = "";
String binFragment = "";
int iHex;
hex = hex.trim();
hex = hex.replaceFirst("0x", "");
for(int i = 0; i < hex.length(); i++){
iHex = Integer.parseInt(""+hex.charAt(i),16);
binFragment = Integer.toBinaryString(iHex);
while(binFragment.length() < 4){
binFragment = "0" + binFragment;
}
bin += binFragment;
}
return bin;
}
上述方法基本上将十六进制字符串中的每个字符转换为等效的二进制,必要时用零填充,然后将其连接到返回值.这是执行转换的正确方法吗?还是我忽略了一些可能导致我的方法失败的事情?
The above method basically takes each character in the Hex string and converts it to its binary equivalent pads it with zeros if necessary then joins it to the return value. Is this a proper way of performing a conversion? Or am I overlooking something that may cause my approach to fail?
提前感谢您的帮助.
推荐答案
BigInteger.toString(radix)
会做你想做的事.只需传入一个基数 2.
BigInteger.toString(radix)
will do what you want. Just pass in a radix of 2.
static String hexToBin(String s) {
return new BigInteger(s, 16).toString(2);
}
相关文章