【问题标题】:Split BigInteger into nibble array将 BigInteger 拆分为半字节数组
【发布时间】:2014-05-30 15:25:39
【问题描述】:

有没有办法可以将BigInteger 拆分成一个半字节数组(4 位段)?有一种内置方法可以获取字节数组BigInteger.toByteArray(),但没有获取半字节的方法。

【问题讨论】:

  • 你到底为什么要这么做?
  • 我想将任意数字 1-8 列表编码为一个数字。

标签: java bit biginteger nibble


【解决方案1】:

您可以使用从toByteArray() 获得的字节数组创建自己的方法来执行此操作

public static List<Byte> getNibbles(byte[] bytes) {
    List<Byte> nibbles = new ArrayList<Byte>();

    for (byte b : bytes) {
        nibbles.add((byte) (b >> 4));
        nibbles.add((byte) ((b & 0x0f)));
    }

    return nibbles;
}

public static void main(String[] args) {
    BigInteger i = BigInteger.valueOf(4798234);
    System.out.println(Arrays.toString(i.toByteArray()));
    System.out.println(getNibbles(i.toByteArray()));
}

输出

[73, 55, 26]
[4, 9, 3, 7, 1, 10]

获取字节 55。您将最高 4 位和最低 4 位添加到半字节列表中。

55 = 00110111
(55 >> 4) = 00000011 (3)
(55 & 0x0f) = 00000111 (7)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 2015-09-09
    • 1970-01-01
    相关资源
    最近更新 更多