问题描述
我发现下面的方法十六进制二进制的转换:
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?
在此先感谢的任何援助。
Thanks in advance for any assistance.
推荐答案
<$c$c>BigInteger.toString(radix)$c$c>会做你想要什么。只是通过以2:1的基数。
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);
}
这篇关于转换十六进制字符串(十六进制),以二进制字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!