将十六进制字符串(hex)转换为二进制字符串
我发现了以下十六进制到二进制转换的方法:
String binAddr = Integer.toBinaryString(Integer.parseInt(hexAddr, 16));
虽然此方法适用于小十六进制数字,但如下所示的十六进制数字
A14AA1DBDB818F9759
会引发 NumberFormatException。
似乎有效的方法:
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;
}
因此,我编写了以下 方法基本上获取十六进制字符串中的每个字符,并将其转换为其二进制等效值,如有必要,用零填充它,然后将其连接到返回值。 这是执行转换的正确方法吗?或者我是否忽略了一些可能导致我的方法失败的事情?
预先感谢您的任何帮助。
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
Throws a 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
BigInteger.toString( radix)
会做你想做的事。只需传入基数 2 即可。BigInteger.toString(radix)
will do what you want. Just pass in a radix of 2.速度快,适用于大字符串:
Fast, and works for large strings:
将十六进制(字符串)解析为基数为 16 的整数,然后使用 toBinaryString(int) 方法将其转换为二进制字符串
示例
将打印
由 int 处理的最大十六进制 vakue 为 FFFFFFF
即如果传递 FFFFFFF0 ti 将给出错误
Parse hex(String) to integer with base 16 then convert it to Binary String using toBinaryString(int) method
example
Will Print
Max Hex vakue Handled by int is FFFFFFF
i.e. if FFFFFFF0 is passed ti will give error
全零:
With all zeroes: