如何获得任意长度的BigInteger的2的补码值 [英] How to get the 2's complement value of a BigInteger of arbitrary length

查看:152
本文介绍了如何获得任意长度的BigInteger的2的补码值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

BigInteger中是否有一种方法来获取2的补码值? 例如:如果有一个BigInteger带有负值

Is there a method in BigInteger to get the 2's complement value? For eg: if there is a BigInteger with a negative value

BigInteger a = new BigInteger("-173B8EC504479C3E95DEB0460411962F9EF2ECE0D3AACD749BE39E1006FC87B8", 16);

然后我想以BigInteger形式获得2的补码

then I want to get the 2's complement in a BigInteger form

BigInteger b = E8C4713AFBB863C16A214FB9FBEE69D0610D131F2C55328B641D61EFF9037848

我可以从0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF中减去第一个BigInteger以获得第二个BigInteger,但是对于任何长度的BigInteger都有通用的计算方法吗?

I can subtract the first BigInteger from 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF to get the second BigInteger but is there a generic method to calculate this for a BigInteger of any length?

推荐答案

要使 make 的值成为二进制补码,您将不得不操作内容.当然这是不可能的,因此您首先要取出内容,对其进行操作,然后将其放入新的BigInteger:

To make this value its two's complement, you will have to manipulate the contents. That is of course impossible, so you first get the contents out, manipulate them and then get them into a new BigInteger:

public static BigInteger twosComplement(BigInteger original)
{
    // for negative BigInteger, top byte is negative  
    byte[] contents = original.toByteArray();

    // prepend byte of opposite sign
    byte[] result = new byte[contents.length + 1];
    System.arraycopy(contents, 0, result, 1, contents.length);
    result[0] = (contents[0] < 0) ? 0 : (byte)-1;

    // this will be two's complement
    return new BigInteger(result);
}

public static void main(String[] args)
{
    BigInteger a = new BigInteger("-173B8EC504479C3E95DEB0460411962F9EF2ECE0D3AACD749BE39E1006FC87B8", 16);
    BigInteger b = twosComplement(a);

    System.out.println(a.toString(16).toUpperCase());
    System.out.println(b.toString(16).toUpperCase());

    // for comparison, from question:
    System.out.println("E8C4713AFBB863C16A214FB9FBEE69D0610D131F2C55328B641D61EFF9037848");
}

输出:

-173B8EC504479C3E95DEB0460411962F9EF2ECE0D3AACD749BE39E1006FC87B8
E8C4713AFBB863C16A214FB9FBEE69D0610D131F2C55328B641C61EFF9037848
E8C4713AFBB863C16A214FB9FBEE69D0610D131F2C55328B641D61EFF9037848

这个新的BigInteger实际上是两者的补充,而不仅仅是对位的重新解释.

And this new BigInteger is really the two's complement, not just a re-interpretation of the bits.

这篇关于如何获得任意长度的BigInteger的2的补码值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆