biginteger.java

来自「This is a resource based on j2me embedde」· Java 代码 · 共 585 行 · 第 1/2 页

JAVA
585
字号
     * (x.compareTo(y)} &lt;<i>op</i>&gt; {@code 0)}, where     * &lt;<i>op</i>&gt; is one of the six comparison operators.     *     * @param  val BigInteger to which this BigInteger is to be compared.     * @return -1, 0 or 1 as this BigInteger is numerically less than, equal     *         to, or greater than {@code val}.     */    public int compareTo(BigInteger val) {        return (signum==val.signum                ? signum*intArrayCmp(mag, val.mag)                : (signum>val.signum ? 1 : -1));    }    /*     * Returns -1, 0 or +1 as big-endian unsigned int array arg1 is     * less than, equal to, or greater than arg2.     */    private static int intArrayCmp(int[] arg1, int[] arg2) {        if (arg1.length < arg2.length) {            return -1;        }        if (arg1.length > arg2.length) {            return 1;        }        // Argument lengths are equal; compare the values        for (int i=0; i<arg1.length; i++) {            long b1 = arg1[i] & LONG_MASK;            long b2 = arg2[i] & LONG_MASK;            if (b1 < b2) {                return -1;            }            if (b1 > b2) {                return 1;            }        }        return 0;    }    /**     * Compares this BigInteger with the specified Object for equality.     *     * @param  x Object to which this BigInteger is to be compared.     * @return {@code true} if and only if the specified Object is a     *         BigInteger whose value is numerically equal to this BigInteger.     */    public boolean equals(Object x) {        // This test is just an optimization, which may or may not help        if (x == this) {            return true;        }        if (!(x instanceof BigInteger)) {            return false;        }        BigInteger xInt = (BigInteger) x;        if (xInt.signum != signum || xInt.mag.length != mag.length) {            return false;        }        for (int i = 0; i < mag.length; i++) {            if (xInt.mag[i] != mag[i]) {                return false;            }        }        return true;    }    // Hash Function    /**     * Returns the hash code for this BigInteger.     *     * @return hash code for this BigInteger.     */    public int hashCode() {        int hashCode = 0;        for (int i=0; i<mag.length; i++)            hashCode = (int)(31*hashCode + (mag[i] & LONG_MASK));        return hashCode * signum;    }    /**     * Returns a byte array containing the two's-complement     * representation of this BigInteger.  The byte array will be in     * <i>big-endian</i> byte-order: the most significant byte is in     * the zeroth element.  The array will contain the minimum number     * of bytes required to represent this BigInteger, including at     * least one sign bit, which is {@code (ceil((this.bitLength() +     * 1)/8))}.  (This representation is compatible with the     * {@link #BigInteger(byte[]) (byte[])} constructor.)     *     * @return a byte array containing the two's-complement representation of     *         this BigInteger.     * @see    #BigInteger(byte[])     */    public byte[] toByteArray() {        int byteLen = bitLength()/8 + 1;        byte[] byteArray = new byte[byteLen];        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;    }    /**     * Converts this BigInteger to an {@code int}.  This     * conversion is analogous to a <a     * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing     * primitive conversion</i></a> from {@code long} to     * {@code int} as defined in the <a     * href="http://java.sun.com/docs/books/jls/html/">Java Language     * Specification</a>: if this BigInteger is too big to fit in an     * {@code int}, only the low-order 32 bits are returned.     * Note that this conversion can lose information about the     * overall magnitude of the BigInteger value as well as return a     * result with the opposite sign.     *     * @return this BigInteger converted to an {@code int}.     */    public int intValue() {        int result = 0;        result = getInt(0);        return result;    }    /**     * Converts this BigInteger to a {@code long}.  This     * conversion is analogous to a <a     * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing     * primitive conversion</i></a> from {@code long} to     * {@code int} as defined in the <a     * href="http://java.sun.com/docs/books/jls/html/">Java Language     * Specification</a>: if this BigInteger is too big to fit in a     * {@code long}, only the low-order 64 bits are returned.     * Note that this conversion can lose information about the     * overall magnitude of the BigInteger value as well as return a     * result with the opposite sign.     *     * @return this BigInteger converted to a {@code long}.     */    public long longValue() {        long result = 0;        for (int i=1; i>=0; i--)            result = (result << 32) + (getInt(i) & LONG_MASK);        return result;    }    /**     * Returns a copy of the input array stripped of any leading zero bytes.     */    private static int[] stripLeadingZeroBytes(byte a[]) {        int byteLength = a.length;        int keep;        // Find first nonzero byte        for (keep=0; keep<a.length && a[keep]==0; keep++)            ;        // Allocate new array and copy relevant part of input array        int intLength = ((byteLength - keep) + 3)/4;        int[] result = new int[intLength];        int b = byteLength - 1;        for (int i = intLength-1; i >= 0; i--) {            result[i] = a[b--] & 0xff;            int bytesRemaining = b - keep + 1;            int bytesToTransfer = Math.min(3, bytesRemaining);            for (int j=8; j <= 8*bytesToTransfer; j += 8) {                result[i] |= ((a[b--] & 0xff) << j);            }        }        return result;    }    /**     * Takes an array a representing a negative 2's-complement number and     * returns the minimal (no leading zero bytes) unsigned whose value is -a.     */    private static int[] makePositive(byte a[]) {        int keep, k;        int byteLength = a.length;        // Find first non-sign (0xff) byte of input        for (keep=0; keep<byteLength && a[keep]==-1; keep++)            ;        /* Allocate output array.  If all non-sign bytes are 0x00, we must         * allocate space for one extra output byte. */        for (k=keep; k<byteLength && a[k]==0; k++)            ;        int extraByte = (k==byteLength) ? 1 : 0;        int intLength = ((byteLength - keep + extraByte) + 3)/4;        int result[] = new int[intLength];        /* Copy one's complement of input into output, leaving extra         * byte (if it exists) == 0x00 */        int b = byteLength - 1;        for (int i = intLength-1; i >= 0; i--) {            result[i] = a[b--] & 0xff;            int numBytesToTransfer = Math.min(3, b-keep+1);            if (numBytesToTransfer < 0)                numBytesToTransfer = 0;            for (int j=8; j <= 8*numBytesToTransfer; j += 8)                result[i] |= ((a[b--] & 0xff) << j);            // Mask indicates which bits must be complemented            int mask = -1 >>> (8*(3-numBytesToTransfer));            result[i] = ~result[i] & mask;        }        // Add one to one's complement to generate two's complement        for (int i=result.length-1; i>=0; i--) {            result[i] = (int)((result[i] & LONG_MASK) + 1);            if (result[i] != 0)                break;        }        return result;    }    /* Returns an int of sign bits */    private int signInt() {        return signum < 0 ? -1 : 0;    }    /**     * Returns the specified int of the little-endian two's complement     * representation (int 0 is the least significant).  The int number can     * be arbitrarily high (values are logically preceded by infinitely many     * sign ints).     */    private int getInt(int n) {        if (n < 0)            return 0;        if (n >= mag.length)            return signInt();        int magInt = mag[mag.length-n-1];        return (signum >= 0 ? magInt :                (n <= firstNonzeroIntNum() ? -magInt : ~magInt));    }    /**     * Returns the index of the int that contains the first nonzero int in the     * little-endian binary representation of the magnitude (int 0 is the     * least significant). If the magnitude is zero, return value is undefined.     */     private int firstNonzeroIntNum() {        /*         * Initialize firstNonzeroIntNum field the first time this method is         * executed. This method depends on the atomicity of int modifies;         * without this guarantee, it would have to be synchronized.         */        if (firstNonzeroIntNum == -2) {            // Search for the first nonzero int            int i;            for (i=mag.length-1; i>=0 && mag[i]==0; i--)                ;            firstNonzeroIntNum = mag.length-i-1;        }        return firstNonzeroIntNum;    }        /**     * return a hexadecimal printed representation of the specified     * BigInteger object. the value is formatted to fit on lines of     * at least 75 characters, with embedded newlines. Words are     * separated for readability, with eight words (32 bytes) per line.     */    public static String toHexString(BigInteger b) {        return (b == null) ? "" : Utils.hexEncode(b.toByteArray());    }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?