【问题标题】:How to convert 160 digit binary string to 20 byte array? [duplicate]如何将 160 位二进制字符串转换为 20 字节数组? [复制]
【发布时间】:2013-07-09 09:14:40
【问题描述】:

我有一个包含 160 位数字的二进制字符串。 我试过了:

new BigInteger("0000000000000000000000000000000000000000000000010000000000000000000000000000001000000000010000011010000000000000000000000000000000000000000000000000000000000000", 2).toByteArray()

但它返回的 15 字节数组已删除前导 0 字节。

我想保留那些前导 0 字节,保留 20 个字节。

我知道其他一些方法可以实现这一点,但我想知道是否有更简单的方法可能只需要几行代码。

【问题讨论】:

  • 您可以通过8-currentSize 左侧的值为 0 的元素扩展您的数组
  • 提供binStr 的示例和预期输出?
  • @anubhava OP的代码行暗示:binStr = "0011010111...11"; array = {120, -145, ..., 20}.
  • 你仍然不能在 8 个字节中存储 160 位 - 你需要 20 个字节。
  • 您可以使用 System.arraycopy 复制复制到 8 字节数组

标签: java


【解决方案1】:

类似这样的代码应该适合你:

byte[] src = new BigInteger(binStr, 2).toByteArray();
byte[] dest = new byte[(binStr.length()+7)/8]; // 20 bytes long for String of 160 length
System.arraycopy(src, 0, dest, 20 - src.length, src.length);
// testing
System.out.printf("Bytes: %d:%s%n", dest.length, Arrays.toString(dest));

输出:

Bytes: 20:[0, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 65, -96, 0, 0, 0, 0, 0, 0, 0]

【讨论】:

    【解决方案2】:

    为什么不简单:

    public static byte[] convert160bitsToBytes(String binStr) {
        byte[] a = new BigInteger(binStr, 2).toByteArray();
        byte[] b = new byte[20];
        int i = 20 - a.length;
        int j = 0;
        if (i < 0) throw new IllegalArgumentException("string was too long");
        for (; j < a.length; j++,i++) {
            b[i] = a[j];
        }
        return b;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-17
      • 2019-03-14
      • 1970-01-01
      • 1970-01-01
      • 2020-05-06
      • 2021-12-20
      • 2021-12-05
      相关资源
      最近更新 更多