問題描述
我找到了以下十六進制到二進制轉換的方式:
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);
}
這篇關于將十六進制字符串(hex)轉換為二進制字符串的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!