将十六进制字符串(hex)转换为二进制字符串

Convert hexadecimal string (hex) to a binary string(将十六进制字符串(hex)转换为二进制字符串)
本文介绍了将十六进制字符串(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)转换为二进制字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Fastest way to generate all binary strings of size n into a boolean array?(将所有大小为 n 的二进制字符串生成为布尔数组的最快方法?)
Convert integer to zero-padded binary string(将整数转换为零填充的二进制字符串)
How Can I Convert Very Large Decimal Numbers to Binary In Java(如何在 Java 中将非常大的十进制数转换为二进制数)
Check if only one single bit is set within an integer (whatever its position)(检查整数中是否只设置了一个位(无论其位置如何))
Embed a Executable Binary in a shell script(在 shell 脚本中嵌入可执行二进制文件)
why does quot;STRINGquot;.getBytes() work different according to the Operation System(为什么“STRING.getBytes() 的工作方式因操作系统而异)