java - 如何将2048位的BigInteger分割成固定数量的64位的字?

标签 java biginteger

我有一个包含 2048 位 BigInteger 数字的 key 。我想将其分解为固定数量的 64 位字,然后计算所有这些字的异或;谁能帮我用java实现这个?

示例:

Big Number(key): 11380312415897726212538720767584623938377542218843650885786488543557849920563944820657401556147072220807050423844611527817088743264179887246035449031879964033048917437051768727745163996083995699396309860629605332639267450328379289961205789359923142431676348109877819086396004913235006262427231898532203764657706261780748597526471127787542155628754978941021278802504747939847153450812209928520258539639347968927907337576400038705453704498741239631581573919339705649004208586949422810873621196157474272177586468236634536851618181572350294408509526514361027546939234421045026063811415872877733865949984217287267027217419

output(parity checksum:) 10249015871569703692

这是我实现的方法,但它无法正常工作:

 /**
     * *
     * Receives a 2048 bits key and applies a word by word XOR to yield a 64 bit
     * integer at the end.
     *
     * @param key 2048 bit integer form part A1 DH Key Exchange Protocol
     * @return A 64 bit integer
     */
    public static BigInteger parityWordChecksum(BigInteger key) {

        LongBuffer buffer = ByteBuffer.wrap(key.toByteArray()).asLongBuffer();
        long xor = 0;
        while (buffer.hasRemaining()) {
            xor ^= buffer.get();
        }
        return BigInteger.valueOf(xor);
    }

最佳答案

如果您只想在方法中使用 BigInteger(而不是 long),您可以这样做:

public static BigInteger parityWordChecksum(final BigInteger key) {
    BigInteger result = new BigInteger("0");

    BigInteger mask = BigInteger.ZERO;
    for (int i = 0; i < 64; i++) {
        mask = mask.setBit(i);
    }

    for (int i = 0; i < 2048; i += 64) {
        result = result.xor(key.shiftRight(i).and(mask));
    }

    return result;
}

关于java - 如何将2048位的BigInteger分割成固定数量的64位的字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32755497/

相关文章:

java - 如何限制 spring security 可保护的类?

java - 如何计算 2 的幂 N 其中 N 是一个非常大的数

当数据类型为 bigint(8) 但作为 bigint(20) 失败时,mysql 排序功能正常

java - 如何制作使用数字加法的模板类(其中模板扩展了 Number)?

Java 与 C# : BigInteger hex string yields different result?

java - BigDecimal 与 BigInteger 和 BigDecimal 的性能比较

java - BigInteger 使用多少空间?

java - NullPointerException 和编码

java - 接收安卓短信

java - 交换内存不足