1. 程式人生 > >Java中BigInteger型別

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; }