Java中BigInteger类型

BigInteger是java.math包提供的处理大整数类型,实现了大整数的存储,四则运算,判断素数的方法,求幂,求模,求逆元,求最大公约数等方法。本文主要分析下BigInteger对于大整数的存储和几个常用函数的实现。

toByteArray函数实现:

    public byte[] toByteArray() {
        int byteLen = bitLength()/8 + 1;
        byte[] byteArray = new byte[byteLen];

//每次从mag数组中取出一个整数,低字节存在低地址,高字节存在高地址 for (int i=byteLen-1, bytesCopied=4, nextInt=0, intIndex=0; i >= 0; i--) { if (bytesCopied == 4) { nextInt = getInt(intIndex++); bytesCopied = 1; } else { nextInt >>>= 8; bytesCopied++; } byteArray[i] = (byte)nextInt; } return byteArray; }