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)转换为二进制字符串


- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01