Convert hexadecimal string (hex) to a binary string(将十六进制字符串(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);
}
这篇关于将十六进制字符串(hex)转换为二进制字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将十六进制字符串(hex)转换为二进制字符串
基础教程推荐
- 降序排序:Java Map 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01