Java Code Examples for java.math.BigInteger#testBit()

The following examples show how to use java.math.BigInteger#testBit() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Override
public BitSet serialize(BigInteger number, int size, boolean signed) {
    if (size == 1) {
        signed = false;
    }
    BitSet bitSet = new BitSet(size);

    int length = Math.min(size, BIG_INTEGER_MAX_SIZE);
    for (int i = 0; i < length - (signed ? 1 : 0); i++) {
        if (number.testBit(i)) {
            bitSet.set(i);
        }
    }
    if (signed && number.signum() == -1) {
        bitSet.set(length - 1);
    }
    return bitSet;
}
 
Example 2
Source Project: astor   File: MathUtils.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Raise a BigInteger to a BigInteger power.
 *
 * @param k Number to raise.
 * @param e Exponent (must be positive or zero).
 * @return k<sup>e</sup>
 * @throws NotPositiveException if {@code e < 0}.
 */
public static BigInteger pow(final BigInteger k, BigInteger e) {
    if (e.compareTo(BigInteger.ZERO) < 0) {
        throw new NotPositiveException(LocalizedFormats.EXPONENT, e);
    }

    BigInteger result = BigInteger.ONE;
    BigInteger k2p    = k;
    while (!BigInteger.ZERO.equals(e)) {
        if (e.testBit(0)) {
            result = result.multiply(k2p);
        }
        k2p = k2p.multiply(k2p);
        e = e.shiftRight(1);
    }

    return result;
}
 
Example 3
public static Point sumOfTwoMultiplies(Point P, BigInteger k, Point Q, BigInteger l) {
   int m = Math.max(k.bitLength(), l.bitLength());
   Point Z = P.add(Q);
   Point R = P.getCurve().getInfinity();

   for (int i = m - 1; i >= 0; --i) {
      R = R.twice();

      if (k.testBit(i)) {
         if (l.testBit(i)) {
            R = R.add(Z);
         } else {
            R = R.add(P);
         }
      } else {
         if (l.testBit(i)) {
            R = R.add(Q);
         }
      }
   }

   return R;
}
 
Example 4
Source Project: hipparchus   File: ArithmeticUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Raise a BigInteger to a BigInteger power.
 *
 * @param k Number to raise.
 * @param e Exponent (must be positive or zero).
 * @return k<sup>e</sup>
 * @throws MathIllegalArgumentException if {@code e < 0}.
 */
public static BigInteger pow(final BigInteger k, BigInteger e) throws MathIllegalArgumentException {
    if (e.compareTo(BigInteger.ZERO) < 0) {
        throw new MathIllegalArgumentException(LocalizedCoreFormats.EXPONENT, e);
    }

    BigInteger result = BigInteger.ONE;
    BigInteger k2p    = k;
    while (!BigInteger.ZERO.equals(e)) {
        if (e.testBit(0)) {
            result = result.multiply(k2p);
        }
        k2p = k2p.multiply(k2p);
        e = e.shiftRight(1);
    }

    return result;
}
 
Example 5
Source Project: coming   File: Cardumen_0053_s.java    License: MIT License 6 votes vote down vote up
/**
 * Raise a BigInteger to a BigInteger power.
 * @param k number to raise
 * @param e exponent (must be positive or null)
 * @return k<sup>e</sup>
 * @exception IllegalArgumentException if e is negative
 */
public static BigInteger pow(final BigInteger k, BigInteger e)
    throws IllegalArgumentException {

    if (e.compareTo(BigInteger.ZERO) < 0) {
        throw MathRuntimeException.createIllegalArgumentException(
            LocalizedFormats.POWER_NEGATIVE_PARAMETERS,
            k, e);
    }

    BigInteger result = BigInteger.ONE;
    BigInteger k2p    = k;
    while (!BigInteger.ZERO.equals(e)) {
        if (e.testBit(0)) {
            result = result.multiply(k2p);
        }
        k2p = k2p.multiply(k2p);
        e = e.shiftRight(1);
    }

    return result;

}
 
Example 6
Source Project: coming   File: NPEfix13_thirteen_s.java    License: MIT License 6 votes vote down vote up
/**
 * Raise a BigInteger to a BigInteger power.
 * @param k number to raise
 * @param e exponent (must be positive or null)
 * @return k<sup>e</sup>
 * @exception IllegalArgumentException if e is negative
 */
public static BigInteger pow(final BigInteger k, BigInteger e)
        throws IllegalArgumentException {

    if (e.compareTo(BigInteger.ZERO) < 0) {
        throw MathRuntimeException.createIllegalArgumentException(
                "cannot raise an integral value to a negative power ({0}^{1})",
                k, e);
    }

    BigInteger result = BigInteger.ONE;
    BigInteger k2p    = k;
    while (!BigInteger.ZERO.equals(e)) {
        if (e.testBit(0)) {
            result = result.multiply(k2p);
        }
        k2p = k2p.multiply(k2p);
        e = e.shiftRight(1);
    }

    return result;

}
 
Example 7
private static BigInteger[] lucasSequence(BigInteger p, BigInteger P, BigInteger Q, BigInteger k) {
    int n = k.bitLength();
    int s = k.getLowestSetBit();

    BigInteger Uh = BigInteger.ONE;
    BigInteger Vl = TWO;
    BigInteger Vh = P;
    BigInteger Ql = BigInteger.ONE;
    BigInteger Qh = BigInteger.ONE;

    for (int j = n - 1; j >= s + 1; --j) {
        Ql = Ql.multiply(Qh).mod(p);

        if (k.testBit(j)) {
            Qh = Ql.multiply(Q).mod(p);
            Uh = Uh.multiply(Vh).mod(p);
            Vl = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p);
            Vh = Vh.multiply(Vh).subtract(Qh.shiftLeft(1)).mod(p);
        } else {
            Qh = Ql;
            Uh = Uh.multiply(Vl).subtract(Ql).mod(p);
            Vh = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p);
            Vl = Vl.multiply(Vl).subtract(Ql.shiftLeft(1)).mod(p);
        }
    }

    Ql = Ql.multiply(Qh).mod(p);
    Qh = Ql.multiply(Q).mod(p);
    Uh = Uh.multiply(Vl).subtract(Ql).mod(p);
    Vl = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p);
    Ql = Ql.multiply(Qh).mod(p);

    for (int j = 1; j <= s; ++j) {
        Uh = Uh.multiply(Vl).mod(p);
        Vl = Vl.multiply(Vl).subtract(Ql.shiftLeft(1)).mod(p);
        Ql = Ql.multiply(Ql).mod(p);
    }

    return new BigInteger[] { Uh, Vl };
}
 
Example 8
Source Project: ripple-lib-java   File: DiscoverEndomorphisms.java    License: ISC License 5 votes vote down vote up
private static BigInteger solveQuadraticEquation(BigInteger n, BigInteger r, BigInteger s)
{
    BigInteger det = r.multiply(r).subtract(s.shiftLeft(2)).mod(n);

    BigInteger root = new ECFieldElement.Fp(n, det).sqrt().toBigInteger();
    if (!root.testBit(0))
    {
        root = n.subtract(root);
    }

    return root.shiftRight(1); // NOTE: implicit -1 of the low-bit
}
 
Example 9
private static BigInteger solveQuadraticEquation(BigInteger n, BigInteger r, BigInteger s)
{
    BigInteger det = r.multiply(r).subtract(s.shiftLeft(2)).mod(n);

    BigInteger root = new ECFieldElement.Fp(n, det).sqrt().toBigInteger();
    if (!root.testBit(0))
    {
        root = n.subtract(root);
    }

    return root.shiftRight(1); // NOTE: implicit -1 of the low-bit
}
 
Example 10
Source Project: Bytecoder   File: IntegerModuloP.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Calculate the power this^b and return the result.
 *
 * @param b the exponent
 * @return the value of this^b
 */
default ImmutableIntegerModuloP pow(BigInteger b) {
    //Default implementation is square and multiply
    MutableIntegerModuloP y = getField().get1().mutable();
    MutableIntegerModuloP x = mutable();
    int bitLength = b.bitLength();
    for (int bit = 0; bit < bitLength; bit++) {
        if (b.testBit(bit)) {
            // odd
            y.setProduct(x);
        }
        x.setSquare();
    }
    return y.fixed();
}
 
Example 11
/**
 * @param N
 * @return first prime > N
 */
public BigInteger nextProbablePrime(BigInteger N) {
	// Java's built-in function using a sieve to identify prime candidates is stronger for N>=256 bit.
	if (N.bitLength()>=256) return N.nextProbablePrime();
	
    N = N.abs(); // sign is irrelevant
    if (N.bitLength()<=1) return I_2;
	// skip argument and make even argument odd
    N = N.testBit(0) ? N.add(I_2) : N.add(I_1);
	
	// loop to next prime
	while (!isProbablePrime(N)) N = N.add(I_2);
	return N;
}
 
Example 12
/**
 * Calculate the power this^b and return the result.
 *
 * @param b the exponent
 * @return the value of this^b
 */
default ImmutableIntegerModuloP pow(BigInteger b) {
    //Default implementation is square and multiply
    MutableIntegerModuloP y = getField().get1().mutable();
    MutableIntegerModuloP x = mutable();
    int bitLength = b.bitLength();
    for (int bit = 0; bit < bitLength; bit++) {
        if (b.testBit(bit)) {
            // odd
            y.setProduct(x);
        }
        x.setSquare();
    }
    return y.fixed();
}
 
Example 13
Source Project: Java8CN   File: IndexColorModel.java    License: Apache License 2.0 5 votes vote down vote up
private void setRGBs(int size, int cmap[], int start, boolean hasalpha) {
    map_size = size;
    rgb = new int[calcRealMapSize(pixel_bits, size)];
    int j = start;
    int transparency = OPAQUE;
    boolean allgray = true;
    BigInteger validBits = this.validBits;
    for (int i = 0; i < size; i++, j++) {
        if (validBits != null && !validBits.testBit(i)) {
            continue;
        }
        int cmaprgb = cmap[j];
        int r = (cmaprgb >> 16) & 0xff;
        int g = (cmaprgb >>  8) & 0xff;
        int b = (cmaprgb      ) & 0xff;
        allgray = allgray && (r == g) && (g == b);
        if (hasalpha) {
            int alpha = cmaprgb >>> 24;
            if (alpha != 0xff) {
                if (alpha == 0x00) {
                    if (transparency == OPAQUE) {
                        transparency = BITMASK;
                    }
                    if (transparent_index < 0) {
                        transparent_index = i;
                    }
                } else {
                    transparency = TRANSLUCENT;
                }
                allgray = false;
            }
        } else {
            cmaprgb |= 0xff000000;
        }
        rgb[i] = cmaprgb;
    }
    this.allgrayopaque = allgray;
    setTransparency(transparency);
}
 
Example 14
Source Project: wycheproof   File: DsaTest.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Checks whether the one time key k in DSA is biased. For example the SUN provider fell for this
 * test until April 2016.
 */
@SuppressWarnings("InsecureCryptoUsage")
@Test
public void testDsaBias() throws Exception {
  // q is close to 2/3 * 2^160.
  BigInteger q = new BigInteger("974317976835659416858874959372334979171063697271");
  BigInteger p =
      new BigInteger(
          "1106803511314772711673172950296693567629309594518393175860816428"
              + "6658764043763662129010863568011543182924292444458455864283745070"
              + "9908516713302345161980412667892373845670780253725557376379049862"
              + "4062950082444499320797079243439689601679418602390654466821968220"
              + "32212146727497041502702331623782703855119908989712161");
  BigInteger g =
      new BigInteger(
          "1057342118316953575810387190942009018497979302261477972033090351"
              + "7561815639397594841480480197745063606756857212792356354588585967"
              + "3837265237205154744016475608524531648654928648461175919672511710"
              + "4878976887505840764543501512668232945506391524642105449699321960"
              + "32410302985148400531470153936516167243072120845392903");
  BigInteger x = new BigInteger("13706102843888006547723575730792302382646994436");

  KeyFactory kf = KeyFactory.getInstance("DSA");
  DSAPrivateKey priv = (DSAPrivateKey) kf.generatePrivate(new DSAPrivateKeySpec(x, p, q, g));

  // If we make TESTS tests with a fair coin then the probability that
  // either heads or tails appears less than MINCOUNT times is less than
  // 2^{-32}.
  // I.e. 2*sum(binomial(tests,i) for i in range(mincount))*2**32 < 2**tests
  // Therefore the test below is not expected to fail unless the generation
  // of the one time keys is indeed biased.
  final int tests = 1024;
  final int mincount = 410;

  String hashAlgorithm = "SHA";
  String message = "Hello";
  byte[] messageBytes = message.getBytes("UTF-8");
  byte[] digest = MessageDigest.getInstance(hashAlgorithm).digest(messageBytes);
  BigInteger h = new BigInteger(1, digest);

  final BigInteger qHalf = q.shiftRight(1);
  Signature signer = Signature.getInstance("SHA1WithDSA");
  signer.initSign(priv);
  int countLsb = 0; // count the number of k's with msb set
  int countMsb = 0; // count the number of k's with lsb set
  for (int i = 0; i < tests; i++) {
    signer.update(messageBytes);
    byte[] signature = signer.sign();
    BigInteger k = extractK(signature, h, priv, i < 10);
    if (k.testBit(0)) {
      countLsb++;
    }
    if (k.compareTo(qHalf) == 1) {
      countMsb++;
    }
  }
  if (countLsb < mincount || countLsb > tests - mincount) {
    fail("Bias detected in the least significant bit of k:" + countLsb);
  }
  if (countMsb < mincount || countMsb > tests - mincount) {
    fail("Bias detected in the most significant bit of k:" + countMsb);
  }
}
 
Example 15
/**
 * Jacobi symbol J(a|m), with m an odd, positive integer.
 * 
 * Highly optimized, using faster quadratic reciprocity.
 * 
 * @param a
 * @param m an odd integer
 * @return
 */
public int jacobiSymbol/*_v03*/(BigInteger a, BigInteger m) {
   	int aCmpZero = a.compareTo(I_0);
       if (aCmpZero == 0) return 0;

      // make a positive
	int t=1, mMod8;
       if (aCmpZero < 0) {
           a = a.negate();
           mMod8 = m.intValue() & 7; // for m%8 we need only the lowest 3 bits
           if (mMod8==3 || mMod8==7) t = -t;
       }

	a = a.mod(m);
	
	// reduction loop
       int lsb;
	boolean hasOddPowerOf2;
	BigInteger tmp;
	while(!a.equals(I_0)) {
		// make a odd
		lsb = a.getLowestSetBit();
		hasOddPowerOf2 = (lsb&1)==1; // e.g. lsb==1 -> a has one 2
		if (lsb > 1) {
			// powers of 4 do not change t -> remove them in one go
			a = a.shiftRight(hasOddPowerOf2 ? lsb-1 : lsb);
		}
		if (hasOddPowerOf2) {
			a = a.shiftRight(1);
			mMod8 = m.intValue() & 7; // for m%8 we need only the lowest 3 bits
			if (mMod8==3 || mMod8==5) t = -t; // m == 3, 5 (mod 8) -> negate t
		}
		// now both a and m are odd (m was odd from the start!)
		// swap variables
		tmp = a; a = m; m = tmp;
		// quadratic reciprocity: the fact that both a and m are odd allows a very fast test == 3 (mod 4)
		if (a.testBit(1) && m.testBit(1)) t = -t; // a == m == 3 (mod 4)
		// reduce a
		a = a.mod(m);
	}
	return (m.equals(I_1)) ? t : 0;
}
 
Example 16
Source Project: ripple-lib-java   File: WNafUtil.java    License: ISC License 4 votes vote down vote up
/**
 * Computes the Window NAF (non-adjacent Form) of an integer.
 * @param width The width <code>w</code> of the Window NAF. The width is
 * defined as the minimal number <code>w</code>, such that for any
 * <code>w</code> consecutive digits in the resulting representation, at
 * most one is non-zero.
 * @param k The integer of which the Window NAF is computed.
 * @return The Window NAF of the given width, such that the following holds:
 * <code>k = &sum;<sub>i=0</sub><sup>l-1</sup> k<sub>i</sub>2<sup>i</sup>
 * </code>, where the <code>k<sub>i</sub></code> denote the elements of the
 * returned <code>byte[]</code>.
 */
public static byte[] generateWindowNaf(int width, BigInteger k)
{
    if (width == 2)
    {
        return generateNaf(k);
    }

    if (width < 2 || width > 8)
    {
        throw new IllegalArgumentException("'width' must be in the range [2, 8]");
    }
    if (k.signum() == 0)
    {
        return EMPTY_BYTES;
    }

    byte[] wnaf = new byte[k.bitLength() + 1];

    // 2^width and a mask and sign bit set accordingly
    int pow2 = 1 << width;
    int mask = pow2 - 1;
    int sign = pow2 >>> 1;

    boolean carry = false;
    int length = 0, pos = 0;

    while (pos <= k.bitLength())
    {
        if (k.testBit(pos) == carry)
        {
            ++pos;
            continue;
        }

        k = k.shiftRight(pos);

        int digit = k.intValue() & mask;
        if (carry)
        {
            ++digit;
        }

        carry = (digit & sign) != 0;
        if (carry)
        {
            digit -= pow2;
        }

        length += (length > 0) ? pos - 1 : pos;
        wnaf[length++] = (byte)digit;
        pos = width;
    }

    // Reduce the WNAF array to its actual length
    if (wnaf.length > length)
    {
        wnaf = trim(wnaf, length);
    }
    
    return wnaf;
}
 
Example 17
/**
 * Constructs an <code>IndexColorModel</code> from an
 * <code>int</code> array where each <code>int</code> is
 * comprised of red, green, blue, and alpha
 * components in the default RGB color model format.
 * The array must have enough values in it to fill all
 * of the needed component arrays of the specified size.
 * The <code>ColorSpace</code> is the default sRGB space.
 * The transparency value may be any of <code>Transparency.OPAQUE</code>,
 * <code>Transparency.BITMASK</code>,
 * or <code>Transparency.TRANSLUCENT</code>
 * depending on the arguments, as specified
 * in the <a href="#transparency">class description</a> above.
 * The transfer type must be one of <code>DataBuffer.TYPE_BYTE</code>
 * <code>DataBuffer.TYPE_USHORT</code>.
 * The <code>BigInteger</code> object specifies the valid/invalid pixels
 * in the <code>cmap</code> array.  A pixel is valid if the
 * <code>BigInteger</code> value at that index is set, and is invalid
 * if the <code>BigInteger</code> bit  at that index is not set.
 * @param bits the number of bits each pixel occupies
 * @param size the size of the color component array
 * @param cmap the array of color components
 * @param start the starting offset of the first color component
 * @param transferType the specified data type
 * @param validBits a <code>BigInteger</code> object.  If a bit is
 *    set in the BigInteger, the pixel at that index is valid.
 *    If a bit is not set, the pixel at that index
 *    is considered invalid.  If null, all pixels are valid.
 *    Only bits from 0 to the map size are considered.
 * @throws IllegalArgumentException if <code>bits</code> is less
 *           than 1 or greater than 16
 * @throws IllegalArgumentException if <code>size</code> is less
 *           than 1
 * @throws IllegalArgumentException if <code>transferType</code> is not
 *           one of <code>DataBuffer.TYPE_BYTE</code> or
 *           <code>DataBuffer.TYPE_USHORT</code>
 *
 * @since 1.3
 */
public IndexColorModel(int bits, int size, int cmap[], int start,
                       int transferType, BigInteger validBits) {
    super (bits, alphaBits,
           ColorSpace.getInstance(ColorSpace.CS_sRGB),
           true, false, TRANSLUCENT,
           transferType);

    if (bits < 1 || bits > 16) {
        throw new IllegalArgumentException("Number of bits must be between"
                                           +" 1 and 16.");
    }
    if (size < 1) {
        throw new IllegalArgumentException("Map size ("+size+
                                           ") must be >= 1");
    }
    if ((transferType != DataBuffer.TYPE_BYTE) &&
        (transferType != DataBuffer.TYPE_USHORT)) {
        throw new IllegalArgumentException("transferType must be either" +
            "DataBuffer.TYPE_BYTE or DataBuffer.TYPE_USHORT");
    }

    if (validBits != null) {
        // Check to see if it is all valid
        for (int i=0; i < size; i++) {
            if (!validBits.testBit(i)) {
                this.validBits = validBits;
                break;
            }
        }
    }

    setRGBs(size, cmap, start, true);
    calculatePixelMask();
}
 
Example 18
/**
 * Constructs an <code>IndexColorModel</code> from an
 * <code>int</code> array where each <code>int</code> is
 * comprised of red, green, blue, and alpha
 * components in the default RGB color model format.
 * The array must have enough values in it to fill all
 * of the needed component arrays of the specified size.
 * The <code>ColorSpace</code> is the default sRGB space.
 * The transparency value may be any of <code>Transparency.OPAQUE</code>,
 * <code>Transparency.BITMASK</code>,
 * or <code>Transparency.TRANSLUCENT</code>
 * depending on the arguments, as specified
 * in the <a href="#transparency">class description</a> above.
 * The transfer type must be one of <code>DataBuffer.TYPE_BYTE</code>
 * <code>DataBuffer.TYPE_USHORT</code>.
 * The <code>BigInteger</code> object specifies the valid/invalid pixels
 * in the <code>cmap</code> array.  A pixel is valid if the
 * <code>BigInteger</code> value at that index is set, and is invalid
 * if the <code>BigInteger</code> bit  at that index is not set.
 * @param bits the number of bits each pixel occupies
 * @param size the size of the color component array
 * @param cmap the array of color components
 * @param start the starting offset of the first color component
 * @param transferType the specified data type
 * @param validBits a <code>BigInteger</code> object.  If a bit is
 *    set in the BigInteger, the pixel at that index is valid.
 *    If a bit is not set, the pixel at that index
 *    is considered invalid.  If null, all pixels are valid.
 *    Only bits from 0 to the map size are considered.
 * @throws IllegalArgumentException if <code>bits</code> is less
 *           than 1 or greater than 16
 * @throws IllegalArgumentException if <code>size</code> is less
 *           than 1
 * @throws IllegalArgumentException if <code>transferType</code> is not
 *           one of <code>DataBuffer.TYPE_BYTE</code> or
 *           <code>DataBuffer.TYPE_USHORT</code>
 *
 * @since 1.3
 */
public IndexColorModel(int bits, int size, int cmap[], int start,
                       int transferType, BigInteger validBits) {
    super (bits, alphaBits,
           ColorSpace.getInstance(ColorSpace.CS_sRGB),
           true, false, TRANSLUCENT,
           transferType);

    if (bits < 1 || bits > 16) {
        throw new IllegalArgumentException("Number of bits must be between"
                                           +" 1 and 16.");
    }
    if (size < 1) {
        throw new IllegalArgumentException("Map size ("+size+
                                           ") must be >= 1");
    }
    if ((transferType != DataBuffer.TYPE_BYTE) &&
        (transferType != DataBuffer.TYPE_USHORT)) {
        throw new IllegalArgumentException("transferType must be either" +
            "DataBuffer.TYPE_BYTE or DataBuffer.TYPE_USHORT");
    }

    if (validBits != null) {
        // Check to see if it is all valid
        for (int i=0; i < size; i++) {
            if (!validBits.testBit(i)) {
                this.validBits = validBits;
                break;
            }
        }
    }

    setRGBs(size, cmap, start, true);
    calculatePixelMask();
}
 
Example 19
/**
 * Constructs an <code>IndexColorModel</code> from an
 * <code>int</code> array where each <code>int</code> is
 * comprised of red, green, blue, and alpha
 * components in the default RGB color model format.
 * The array must have enough values in it to fill all
 * of the needed component arrays of the specified size.
 * The <code>ColorSpace</code> is the default sRGB space.
 * The transparency value may be any of <code>Transparency.OPAQUE</code>,
 * <code>Transparency.BITMASK</code>,
 * or <code>Transparency.TRANSLUCENT</code>
 * depending on the arguments, as specified
 * in the <a href="#transparency">class description</a> above.
 * The transfer type must be one of <code>DataBuffer.TYPE_BYTE</code>
 * <code>DataBuffer.TYPE_USHORT</code>.
 * The <code>BigInteger</code> object specifies the valid/invalid pixels
 * in the <code>cmap</code> array.  A pixel is valid if the
 * <code>BigInteger</code> value at that index is set, and is invalid
 * if the <code>BigInteger</code> bit  at that index is not set.
 * @param bits the number of bits each pixel occupies
 * @param size the size of the color component array
 * @param cmap the array of color components
 * @param start the starting offset of the first color component
 * @param transferType the specified data type
 * @param validBits a <code>BigInteger</code> object.  If a bit is
 *    set in the BigInteger, the pixel at that index is valid.
 *    If a bit is not set, the pixel at that index
 *    is considered invalid.  If null, all pixels are valid.
 *    Only bits from 0 to the map size are considered.
 * @throws IllegalArgumentException if <code>bits</code> is less
 *           than 1 or greater than 16
 * @throws IllegalArgumentException if <code>size</code> is less
 *           than 1
 * @throws IllegalArgumentException if <code>transferType</code> is not
 *           one of <code>DataBuffer.TYPE_BYTE</code> or
 *           <code>DataBuffer.TYPE_USHORT</code>
 *
 * @since 1.3
 */
public IndexColorModel(int bits, int size, int cmap[], int start,
                       int transferType, BigInteger validBits) {
    super (bits, alphaBits,
           ColorSpace.getInstance(ColorSpace.CS_sRGB),
           true, false, TRANSLUCENT,
           transferType);

    if (bits < 1 || bits > 16) {
        throw new IllegalArgumentException("Number of bits must be between"
                                           +" 1 and 16.");
    }
    if (size < 1) {
        throw new IllegalArgumentException("Map size ("+size+
                                           ") must be >= 1");
    }
    if ((transferType != DataBuffer.TYPE_BYTE) &&
        (transferType != DataBuffer.TYPE_USHORT)) {
        throw new IllegalArgumentException("transferType must be either" +
            "DataBuffer.TYPE_BYTE or DataBuffer.TYPE_USHORT");
    }

    if (validBits != null) {
        // Check to see if it is all valid
        for (int i=0; i < size; i++) {
            if (!validBits.testBit(i)) {
                this.validBits = validBits;
                break;
            }
        }
    }

    setRGBs(size, cmap, start, true);
    calculatePixelMask();
}
 
Example 20
Source Project: Java8CN   File: IndexColorModel.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Constructs an <code>IndexColorModel</code> from an
 * <code>int</code> array where each <code>int</code> is
 * comprised of red, green, blue, and alpha
 * components in the default RGB color model format.
 * The array must have enough values in it to fill all
 * of the needed component arrays of the specified size.
 * The <code>ColorSpace</code> is the default sRGB space.
 * The transparency value may be any of <code>Transparency.OPAQUE</code>,
 * <code>Transparency.BITMASK</code>,
 * or <code>Transparency.TRANSLUCENT</code>
 * depending on the arguments, as specified
 * in the <a href="#transparency">class description</a> above.
 * The transfer type must be one of <code>DataBuffer.TYPE_BYTE</code>
 * <code>DataBuffer.TYPE_USHORT</code>.
 * The <code>BigInteger</code> object specifies the valid/invalid pixels
 * in the <code>cmap</code> array.  A pixel is valid if the
 * <code>BigInteger</code> value at that index is set, and is invalid
 * if the <code>BigInteger</code> bit  at that index is not set.
 * @param bits the number of bits each pixel occupies
 * @param size the size of the color component array
 * @param cmap the array of color components
 * @param start the starting offset of the first color component
 * @param transferType the specified data type
 * @param validBits a <code>BigInteger</code> object.  If a bit is
 *    set in the BigInteger, the pixel at that index is valid.
 *    If a bit is not set, the pixel at that index
 *    is considered invalid.  If null, all pixels are valid.
 *    Only bits from 0 to the map size are considered.
 * @throws IllegalArgumentException if <code>bits</code> is less
 *           than 1 or greater than 16
 * @throws IllegalArgumentException if <code>size</code> is less
 *           than 1
 * @throws IllegalArgumentException if <code>transferType</code> is not
 *           one of <code>DataBuffer.TYPE_BYTE</code> or
 *           <code>DataBuffer.TYPE_USHORT</code>
 *
 * @since 1.3
 */
public IndexColorModel(int bits, int size, int cmap[], int start,
                       int transferType, BigInteger validBits) {
    super (bits, alphaBits,
           ColorSpace.getInstance(ColorSpace.CS_sRGB),
           true, false, TRANSLUCENT,
           transferType);

    if (bits < 1 || bits > 16) {
        throw new IllegalArgumentException("Number of bits must be between"
                                           +" 1 and 16.");
    }
    if (size < 1) {
        throw new IllegalArgumentException("Map size ("+size+
                                           ") must be >= 1");
    }
    if ((transferType != DataBuffer.TYPE_BYTE) &&
        (transferType != DataBuffer.TYPE_USHORT)) {
        throw new IllegalArgumentException("transferType must be either" +
            "DataBuffer.TYPE_BYTE or DataBuffer.TYPE_USHORT");
    }

    if (validBits != null) {
        // Check to see if it is all valid
        for (int i=0; i < size; i++) {
            if (!validBits.testBit(i)) {
                this.validBits = validBits;
                break;
            }
        }
    }

    setRGBs(size, cmap, start, true);
    calculatePixelMask();
}