Ejemplo n.º 1
0
  /**
   * Create a {@link BigFraction} given the numerator and denominator as <code>BigInteger</code>.
   * The {@link BigFraction} is reduced to lowest terms.
   *
   * @param num the numerator, must not be <code>null</code>.
   * @param den the denominator, must not be <code>null</code>.
   * @throws ArithmeticException if the denominator is <code>zero</code>.
   * @throws NullPointerException if the numerator or the denominator is <code>zero</code>.
   */
  public BigFraction(BigInteger num, BigInteger den) {
    if (num == null) {
      throw MathRuntimeException.createNullPointerException("numerator is null");
    }
    if (den == null) {
      throw MathRuntimeException.createNullPointerException("denominator is null");
    }
    if (BigInteger.ZERO.equals(den)) {
      throw MathRuntimeException.createArithmeticException("denominator must be different from 0");
    }
    if (BigInteger.ZERO.equals(num)) {
      numerator = BigInteger.ZERO;
      denominator = BigInteger.ONE;
    } else {

      // reduce numerator and denominator by greatest common denominator
      final BigInteger gcd = num.gcd(den);
      if (BigInteger.ONE.compareTo(gcd) < 0) {
        num = num.divide(gcd);
        den = den.divide(gcd);
      }

      // move sign to numerator
      if (BigInteger.ZERO.compareTo(den) > 0) {
        num = num.negate();
        den = den.negate();
      }

      // store the values in the final fields
      numerator = num;
      denominator = den;
    }
  }
Ejemplo n.º 2
0
  /**
   * Create a fraction given the double value.
   *
   * <p>This constructor behaves <em>differently</em> from {@link #BigFraction(double, double,
   * int)}. It converts the double value exactly, considering its internal bits representation. This
   * does work for all values except NaN and infinities and does not requires any loop or
   * convergence threshold.
   *
   * <p>Since this conversion is exact and since double numbers are sometimes approximated, the
   * fraction created may seem strange in some cases. For example calling <code>
   * new BigFraction(1.0 / 3.0)</code> does <em>not</em> create the fraction 1/3 but the fraction
   * 6004799503160661 / 18014398509481984 because the double number passed to the constructor is not
   * exactly 1/3 (this number cannot be stored exactly in IEEE754).
   *
   * @see #BigFraction(double, double, int)
   * @param value the double value to convert to a fraction.
   * @exception IllegalArgumentException if value is NaN or infinite
   */
  public BigFraction(final double value) throws IllegalArgumentException {
    if (Double.isNaN(value)) {
      throw MathRuntimeException.createIllegalArgumentException("cannot convert NaN value");
    }
    if (Double.isInfinite(value)) {
      throw MathRuntimeException.createIllegalArgumentException("cannot convert infinite value");
    }

    // compute m and k such that value = m * 2^k
    final long bits = Double.doubleToLongBits(value);
    final long sign = bits & 0x8000000000000000L;
    final long exponent = bits & 0x7ff0000000000000L;
    long m = bits & 0x000fffffffffffffL;
    if (exponent != 0) {
      // this was a normalized number, add the implicit most significant bit
      m |= 0x0010000000000000L;
    }
    if (sign != 0) {
      m = -m;
    }
    int k = ((int) (exponent >> 52)) - 1075;
    while (((m & 0x001ffffffffffffeL) != 0) && ((m & 0x1) == 0)) {
      m = m >> 1;
      ++k;
    }

    if (k < 0) {
      numerator = BigInteger.valueOf(m);
      denominator = BigInteger.ZERO.flipBit(-k);
    } else {
      numerator = BigInteger.valueOf(m).multiply(BigInteger.ZERO.flipBit(k));
      denominator = BigInteger.ONE;
    }
  }
Ejemplo n.º 3
0
  /**
   * Create a {@link BigFraction} given the numerator and denominator as {@code BigInteger}. The
   * {@link BigFraction} is reduced to lowest terms.
   *
   * @param num the numerator, must not be {@code null}.
   * @param den the denominator, must not be {@code null}.
   * @throws ZeroException if the denominator is zero.
   * @throws NullArgumentException if either of the arguments is null
   */
  public BigFraction(BigInteger num, BigInteger den) {
    MathUtils.checkNotNull(num, LocalizedFormats.NUMERATOR);
    MathUtils.checkNotNull(den, LocalizedFormats.DENOMINATOR);
    if (BigInteger.ZERO.equals(den)) {
      throw new ZeroException(LocalizedFormats.ZERO_DENOMINATOR);
    }
    if (BigInteger.ZERO.equals(num)) {
      numerator = BigInteger.ZERO;
      denominator = BigInteger.ONE;
    } else {

      // reduce numerator and denominator by greatest common denominator
      final BigInteger gcd = num.gcd(den);
      if (BigInteger.ONE.compareTo(gcd) < 0) {
        num = num.divide(gcd);
        den = den.divide(gcd);
      }

      // move sign to numerator
      if (BigInteger.ZERO.compareTo(den) > 0) {
        num = num.negate();
        den = den.negate();
      }

      // store the values in the final fields
      numerator = num;
      denominator = den;
    }
  }
Ejemplo n.º 4
0
 /** @tests java.math.BigInteger#BigInteger(int, byte[]) */
 @TestTargetNew(
     level = TestLevel.COMPLETE,
     notes = "",
     method = "BigInteger",
     args = {int.class, byte[].class})
 public void test_ConstructorI$B() {
   byte[] myByteArray;
   myByteArray = new byte[] {(byte) 0xFF, (byte) 0xFE};
   bi = new BigInteger(1, myByteArray);
   assertTrue(
       "Incorrect value for pos number", bi.equals(BigInteger.ZERO.setBit(16).subtract(two)));
   bi = new BigInteger(-1, myByteArray);
   assertTrue(
       "Incorrect value for neg number",
       bi.equals(BigInteger.ZERO.setBit(16).subtract(two).negate()));
   myByteArray = new byte[] {(byte) 0, (byte) 0};
   bi = new BigInteger(0, myByteArray);
   assertTrue("Incorrect value for zero", bi.equals(zero));
   myByteArray = new byte[] {(byte) 1};
   try {
     new BigInteger(0, myByteArray);
     fail("Failed to throw NumberFormatException");
   } catch (NumberFormatException e) {
     // correct
   }
 }
Ejemplo n.º 5
0
 private static String fromDecimalToOtherBase(BigInteger base, BigInteger decimalNumber) {
   String value = BigInteger.ZERO.equals(decimalNumber) ? "0" : "";
   int mod = 0;
   while (!BigInteger.ZERO.equals(decimalNumber)) {
     mod = decimalNumber.mod(base).intValue();
     value = baseDigits.substring(mod, mod + 1) + value;
     decimalNumber = decimalNumber.divide(base);
   }
   return value;
 }
 @Override
 public ByteBuffer write(ByteBuffer buff, Object obj) {
   if (!isBigInteger(obj)) {
     return super.write(buff, obj);
   }
   BigInteger x = (BigInteger) obj;
   if (BigInteger.ZERO.equals(x)) {
     buff.put((byte) TAG_BIG_INTEGER_0);
   } else if (BigInteger.ONE.equals(x)) {
     buff.put((byte) TAG_BIG_INTEGER_1);
   } else {
     int bits = x.bitLength();
     if (bits <= 63) {
       buff.put((byte) TAG_BIG_INTEGER_SMALL);
       DataUtils.writeVarLong(buff, x.longValue());
     } else {
       buff.put((byte) TYPE_BIG_INTEGER);
       byte[] bytes = x.toByteArray();
       DataUtils.writeVarInt(buff, bytes.length);
       buff = DataUtils.ensureCapacity(buff, bytes.length);
       buff.put(bytes);
     }
   }
   return buff;
 }
Ejemplo n.º 7
0
  /**
   * Divide the value of this fraction by another, returning the result in reduced form.
   *
   * @param fraction the fraction to divide by, must not be <code>null</code>.
   * @return a {@link BigFraction} instance with the resulting values.
   * @throws NullPointerException if the fraction is <code>null</code>.
   * @throws ArithmeticException if the fraction to divide by is zero.
   */
  public BigFraction divide(final BigFraction fraction) {
    if (BigInteger.ZERO.equals(fraction.numerator)) {
      throw MathRuntimeException.createArithmeticException("denominator must be different from 0");
    }

    return multiply(fraction.reciprocal());
  }
Ejemplo n.º 8
0
 @GwtIncompatible // TODO
 public void testConstantSqrt2PrecomputedBits() {
   assertEquals(
       BigIntegerMath.sqrt(
           BigInteger.ZERO.setBit(2 * BigIntegerMath.SQRT2_PRECOMPUTE_THRESHOLD + 1), FLOOR),
       BigIntegerMath.SQRT2_PRECOMPUTED_BITS);
 }
Ejemplo n.º 9
0
  /** @tests java.math.BigInteger#andNot(java.math.BigInteger) */
  @TestTargetNew(
      level = TestLevel.COMPLETE,
      notes = "",
      method = "andNot",
      args = {java.math.BigInteger.class})
  public void test_andNotLjava_math_BigInteger() {
    for (BigInteger[] element : booleanPairs) {
      BigInteger i1 = element[0], i2 = element[1];
      BigInteger res = i1.andNot(i2);
      int len = Math.max(i1.bitLength(), i2.bitLength()) + 66;
      for (int i = 0; i < len; i++) {
        assertTrue("andNot", (i1.testBit(i) && !i2.testBit(i)) == res.testBit(i));
      }
      // asymmetrical
      i1 = element[1];
      i2 = element[0];
      res = i1.andNot(i2);
      for (int i = 0; i < len; i++) {
        assertTrue("andNot reversed", (i1.testBit(i) && !i2.testBit(i)) == res.testBit(i));
      }
    }

    // regression for HARMONY-4653
    try {
      BigInteger.ZERO.andNot(null);
      fail("should throw NPE");
    } catch (Exception e) {
      // expected
    }
    BigInteger bi = new BigInteger(0, new byte[] {});
    assertEquals(BigInteger.ZERO, bi.andNot(BigInteger.ZERO));
  }
Ejemplo n.º 10
0
    BigInteger getAverage() {
      if (BigInteger.ZERO.equals(count)) {
        return BigInteger.ZERO;
      }

      return total.divide(count);
    }
Ejemplo n.º 11
0
  /**
   * Returns a BigDecimal representation of this fraction. If possible, the returned value will be
   * exactly equal to the fraction. If not, the BigDecimal will have a scale large enough to hold
   * the same number of significant figures as both numerator and denominator, or the equivalent of
   * a double-precision number, whichever is more.
   */
  public BigDecimal toBigDecimal() {
    // Implementation note:  A fraction can be represented exactly in base-10 iff its
    // denominator is of the form 2^a * 5^b, where a and b are nonnegative integers.
    // (In other words, if there are no prime factors of the denominator except for
    // 2 and 5, or if the denominator is 1).  So to determine if this denominator is
    // of this form, continually divide by 2 to get the number of 2's, and then
    // continually divide by 5 to get the number of 5's.  Afterward, if the denominator
    // is 1 then there are no other prime factors.

    // Note: number of 2's is given by the number of trailing 0 bits in the number
    int twos = denominator.getLowestSetBit();
    BigInteger tmpDen = denominator.shiftRight(twos); // x / 2^n === x >> n

    final BigInteger FIVE = BigInteger.valueOf(5);
    int fives = 0;
    BigInteger[] divMod = null;

    // while(tmpDen % 5 == 0) { fives++; tmpDen /= 5; }
    while (BigInteger.ZERO.equals((divMod = tmpDen.divideAndRemainder(FIVE))[1])) {
      fives++;
      tmpDen = divMod[0];
    }

    if (BigInteger.ONE.equals(tmpDen)) {
      // This fraction will terminate in base 10, so it can be represented exactly as
      // a BigDecimal.  We would now like to make the fraction of the form
      // unscaled / 10^scale.  We know that 2^x * 5^x = 10^x, and our denominator is
      // in the form 2^twos * 5^fives.  So use max(twos, fives) as the scale, and
      // multiply the numerator and deminator by the appropriate number of 2's or 5's
      // such that the denominator is of the form 2^scale * 5^scale.  (Of course, we
      // only have to actually multiply the numerator, since all we need for the
      // BigDecimal constructor is the scale.
      BigInteger unscaled = numerator;
      int scale = Math.max(twos, fives);

      if (twos < fives) unscaled = unscaled.shiftLeft(fives - twos); // x * 2^n === x << n
      else if (fives < twos) unscaled = unscaled.multiply(FIVE.pow(twos - fives));

      return new BigDecimal(unscaled, scale);
    }

    // else: this number will repeat infinitely in base-10.  So try to figure out
    // a good number of significant digits.  Start with the number of digits required
    // to represent the numerator and denominator in base-10, which is given by
    // bitLength / log[2](10).  (bitLenth is the number of digits in base-2).
    final double LG10 = 3.321928094887362; // Precomputed ln(10)/ln(2), a.k.a. log[2](10)
    int precision = Math.max(numerator.bitLength(), denominator.bitLength());
    precision = (int) Math.ceil(precision / LG10);

    // If the precision is less than 18 digits, use 18 digits so that the number
    // will be at least as accurate as a cast to a double.  For example, with
    // the fraction 1/3, precision will be 1, giving a result of 0.3.  This is
    // quite a bit different from what a user would expect.
    if (precision < 18) precision = 18;

    return toBigDecimal(precision);
  }
  public Element pow(BigInteger n) {
    if (BigInteger.ZERO.equals(n)) {
      setToOne();
      return this;
    }

    elementPowWind(n);

    return this;
  }
Ejemplo n.º 13
0
  /**
   * Divide the value of this fraction by another, returning the result in reduced form.
   *
   * @param fraction Fraction to divide by, must not be {@code null}.
   * @return a {@link BigFraction} instance with the resulting values.
   * @throws NullArgumentException if the {@code fraction} is {@code null}.
   * @throws ZeroException if the fraction to divide by is zero.
   */
  public BigFraction divide(final BigFraction fraction) {
    if (fraction == null) {
      throw new NullArgumentException(LocalizedFormats.FRACTION);
    }
    if (BigInteger.ZERO.equals(fraction.numerator)) {
      throw new ZeroException(LocalizedFormats.ZERO_DENOMINATOR);
    }

    return multiply(fraction.reciprocal());
  }
Ejemplo n.º 14
0
 /**
  * Returns the <code>String</code> representing this fraction, ie "num / dem" or just "num" if the
  * denominator is one.
  *
  * @return a string representation of the fraction.
  * @see java.lang.Object#toString()
  */
 @Override
 public String toString() {
   String str = null;
   if (BigInteger.ONE.equals(denominator)) {
     str = numerator.toString();
   } else if (BigInteger.ZERO.equals(numerator)) {
     str = "0";
   } else {
     str = numerator + " / " + denominator;
   }
   return str;
 }
Ejemplo n.º 15
0
 @RolesAllowed({Role.ADMIN, Role.OPERATOR})
 public void handleEvent(@Observes ClusterKeyEvent event) {
   log.debug("handleEvent: " + event.getClass().getSimpleName());
   if (SecfsEventType.updateKey.equals(event.getType())
       && event.getKey() != null
       && !BigInteger.ZERO.equals(event.getKey())
       && !event.getKey().equals(secret)) {
     secret = event.getKey();
     log.info("handleEvent: updated secret.");
     if (events != null) {
       events.sendEvent(new KeyEvent(SecfsEventType.newKey));
     }
   }
 }
Ejemplo n.º 16
0
 /** @tests java.math.BigInteger#BigInteger(byte[]) */
 @TestTargetNew(
     level = TestLevel.PARTIAL,
     notes = "NumberFormatException checking missed",
     method = "BigInteger",
     args = {byte[].class})
 public void test_Constructor$B() {
   byte[] myByteArray;
   myByteArray = new byte[] {(byte) 0x00, (byte) 0xFF, (byte) 0xFE};
   bi = new BigInteger(myByteArray);
   assertTrue(
       "Incorrect value for pos number", bi.equals(BigInteger.ZERO.setBit(16).subtract(two)));
   myByteArray = new byte[] {(byte) 0xFF, (byte) 0xFE};
   bi = new BigInteger(myByteArray);
   assertTrue("Incorrect value for neg number", bi.equals(minusTwo));
 }
Ejemplo n.º 17
0
 private void retrieveSecret() {
   if (cache != null) {
     if (secret == null) {
       Object cached = cache.get(SECRET_CACHE_KEY);
       if (cached instanceof BigInteger && !BigInteger.ZERO.equals(cached)) {
         secret = (BigInteger) cached;
         log.info("retrieved secret from cache.");
       }
     }
     if (secret == null) {
       cache.put(SECRET_CACHE_KEY, BigInteger.ZERO);
       log.info("sent NoSecret to cache.");
     }
   }
 }
Ejemplo n.º 18
0
  /** Constructs a new BigFraction from the given BigDecimal object. */
  private static BigFraction valueOfHelper(final BigDecimal d) {
    // BigDecimal format: unscaled / 10^scale.
    BigInteger tmpNumerator = d.unscaledValue();
    BigInteger tmpDenominator = BigInteger.ONE;

    // Special case for d == 0 (math below won't work right)
    // Note: Cannot use d.equals(BigDecimal.ZERO), because
    // BigDecimal.equals()
    // does not consider numbers equal if they have different scales. So,
    // 0.00 is not equal to BigDecimal.ZERO.
    if (tmpNumerator.equals(BigInteger.ZERO)) {
      return BigFraction.ZERO;
    }

    if (d.scale() < 0) {
      tmpNumerator = tmpNumerator.multiply(BigInteger.TEN.pow(-d.scale()));
    } else if (d.scale() > 0) {
      // Now we have the form: unscaled / 10^scale = unscaled / (2^scale *
      // 5^scale)
      // We know then that gcd(unscaled, 2^scale * 5^scale) = 2^commonTwos
      // * 5^commonFives

      // Easy to determine commonTwos
      final int commonTwos = Math.min(d.scale(), tmpNumerator.getLowestSetBit());
      tmpNumerator = tmpNumerator.shiftRight(commonTwos);
      tmpDenominator = tmpDenominator.shiftLeft(d.scale() - commonTwos);

      // Determining commonFives is a little trickier..
      int commonFives = 0;

      BigInteger[] divMod = null;
      // while(commonFives < d.scale() && tmpNumerator % 5 == 0) {
      // tmpNumerator /= 5; commonFives++; }
      while (commonFives < d.scale()
          && BigInteger.ZERO.equals((divMod = tmpNumerator.divideAndRemainder(BIGINT_FIVE))[1])) {
        tmpNumerator = divMod[0];
        commonFives++;
      }

      if (commonFives < d.scale()) {
        tmpDenominator = tmpDenominator.multiply(BIGINT_FIVE.pow(d.scale() - commonFives));
      }
    }
    // else: d.scale() == 0: do nothing

    // Guaranteed there is no gcd, so fraction is in lowest terms
    return new BigFraction(tmpNumerator, tmpDenominator, Reduced.YES);
  }
Ejemplo n.º 19
0
  /** @tests java.math.BigInteger#shiftRight(int) */
  @TestTargetNew(
      level = TestLevel.COMPLETE,
      notes = "",
      method = "shiftRight",
      args = {int.class})
  public void test_shiftRightI() {
    assertTrue("1 >> 0", BigInteger.valueOf(1).shiftRight(0).equals(BigInteger.ONE));
    assertTrue("1 >> 1", BigInteger.valueOf(1).shiftRight(1).equals(BigInteger.ZERO));
    assertTrue("1 >> 63", BigInteger.valueOf(1).shiftRight(63).equals(BigInteger.ZERO));
    assertTrue("1 >> 64", BigInteger.valueOf(1).shiftRight(64).equals(BigInteger.ZERO));
    assertTrue("1 >> 65", BigInteger.valueOf(1).shiftRight(65).equals(BigInteger.ZERO));
    assertTrue("1 >> 1000", BigInteger.valueOf(1).shiftRight(1000).equals(BigInteger.ZERO));
    assertTrue("-1 >> 0", BigInteger.valueOf(-1).shiftRight(0).equals(minusOne));
    assertTrue("-1 >> 1", BigInteger.valueOf(-1).shiftRight(1).equals(minusOne));
    assertTrue("-1 >> 63", BigInteger.valueOf(-1).shiftRight(63).equals(minusOne));
    assertTrue("-1 >> 64", BigInteger.valueOf(-1).shiftRight(64).equals(minusOne));
    assertTrue("-1 >> 65", BigInteger.valueOf(-1).shiftRight(65).equals(minusOne));
    assertTrue("-1 >> 1000", BigInteger.valueOf(-1).shiftRight(1000).equals(minusOne));

    BigInteger a = BigInteger.ONE;
    BigInteger c = bi3;
    BigInteger E = bi3.negate();
    BigInteger e = E;
    for (int i = 0; i < 200; i++) {
      BigInteger b = BigInteger.ZERO.setBit(i);
      assertTrue("a==b", a.equals(b));
      a = a.shiftLeft(1);
      assertTrue("a non-neg", a.signum() >= 0);

      BigInteger d = bi3.shiftRight(i);
      assertTrue("c==d", c.equals(d));
      c = c.shiftRight(1);
      assertTrue(">>1 == /2", d.divide(two).equals(c));
      assertTrue("c non-neg", c.signum() >= 0);

      BigInteger f = E.shiftRight(i);
      assertTrue("e==f", e.equals(f));
      e = e.shiftRight(1);
      assertTrue(">>1 == /2", f.subtract(one).divide(two).equals(e));
      assertTrue("e negative", e.signum() == -1);

      assertTrue("b >> i", b.shiftRight(i).equals(one));
      assertTrue("b >> i+1", b.shiftRight(i + 1).equals(zero));
      assertTrue("b >> i-1", b.shiftRight(i - 1).equals(two));
    }
  }
Ejemplo n.º 20
0
 @Override
 public void write(WriteBuffer buff, Object obj) {
   if (!isBigInteger(obj)) {
     super.write(buff, obj);
     return;
   }
   BigInteger x = (BigInteger) obj;
   if (BigInteger.ZERO.equals(x)) {
     buff.put((byte) TAG_BIG_INTEGER_0);
   } else if (BigInteger.ONE.equals(x)) {
     buff.put((byte) TAG_BIG_INTEGER_1);
   } else {
     int bits = x.bitLength();
     if (bits <= 63) {
       buff.put((byte) TAG_BIG_INTEGER_SMALL).putVarLong(x.longValue());
     } else {
       byte[] bytes = x.toByteArray();
       buff.put((byte) TYPE_BIG_INTEGER).putVarInt(bytes.length).put(bytes);
     }
   }
 }
Ejemplo n.º 21
0
 public boolean isZero() {
   return BigInteger.ZERO.equals(value);
 }
Ejemplo n.º 22
0
 public boolean isSqr() {
   return BigInteger.ZERO.equals(value) || BigIntegerUtils.legendre(value, field.order) == 1;
 }
Ejemplo n.º 23
0
public class StringConvertors {

  static SimpleDateFormat sdf = new SimpleDateFormat("yyyy/DDD HH:mm:ss.SSS");
  static final BigInteger B64 = BigInteger.ZERO.setBit(64);

  public static String toString(Value rv) {
    switch (rv.getType()) {
      case BINARY:
        return "(BINARY)" + arrayToHexString(rv.getBinaryValue());
      case DOUBLE:
        return "(DOUBLE)" + rv.getDoubleValue();
      case FLOAT:
        return "(FLOAT)" + rv.getFloatValue();
      case SINT32:
        return "(SIGNED_INTEGER)" + rv.getSint32Value();
      case UINT32:
        return "(UNSIGNED_INTEGER)" + Long.toString(rv.getUint32Value() & 0xFFFFFFFFL);
      case SINT64:
        return "(SIGNED_INTEGER)" + rv.getSint64Value();
      case UINT64:
        return "(UNSIGNED_INTEGER)" + rv.getUint64Value();
      case STRING:
        return "(STRING)" + rv.getStringValue();
      case BOOLEAN:
        return "(BOOLEAN)" + rv.getBooleanValue();
      case TIMESTAMP:
        return "(TIMESTAMP)" + TimeEncoding.toOrdinalDateTime(rv.getTimestampValue());
    }
    return null;
  }

  public static String toString(Value rv, boolean withType) {
    if (withType) return toString(rv);
    switch (rv.getType()) {
      case BINARY:
        return arrayToHexString(rv.getBinaryValue());
      case DOUBLE:
        return Double.toString(rv.getDoubleValue());
      case FLOAT:
        return Float.toString(rv.getFloatValue());
      case SINT32:
        return Integer.toString(rv.getSint32Value());
      case UINT32:
        return Long.toString(rv.getUint32Value() & 0xFFFFFFFFL);
      case SINT64:
        return Long.toString(rv.getSint64Value());
      case UINT64:
        if (rv.getUint64Value() >= 0) return Long.toString(rv.getUint64Value());
        else return BigInteger.valueOf(rv.getUint64Value()).add(B64).toString();
      case STRING:
        return rv.getStringValue();
      case BOOLEAN:
        return Boolean.toString(rv.getBooleanValue());
      case TIMESTAMP:
        return TimeEncoding.toOrdinalDateTime(rv.getTimestampValue());
    }
    return null;
  }

  public static String arrayToHexString(byte[] b) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < b.length; i++) {
      String s = Integer.toString(b[i] & 0xFF, 16);
      if (s.length() == 1) s = "0" + s;
      sb.append(s.toUpperCase());
    }
    return sb.toString();
  }

  public static String byteBufferToHexString(ByteBuffer bb) {
    bb.mark();
    StringBuilder sb = new StringBuilder();
    int offset = 0;
    while (bb.hasRemaining()) {
      if (offset % 33 == 0) sb.append("\n");
      String s = Integer.toString(bb.get() & 0xFF, 16);
      offset++;
      if (s.length() == 1) sb.append("0");
      sb.append(s.toUpperCase());
    }
    bb.reset();
    return sb.toString();
  }

  public static String ccsdsArrayToHexString(byte[] b) {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < b.length; i++) {
      String s = Integer.toString(b[i] & 0xFF, 16);
      if (s.length() == 1) s = "0" + s;
      sb.append(s.toUpperCase());
      if ((i == 5) || (i == 15) || (i == 19)) sb.append("|");
    }
    return sb.toString();
  }

  /**
   * Convert a hex string into a byte array. No check is done if the string has an even number of
   * hex digits. The last one is ignored in case the number is odd.
   *
   * @param s
   * @return
   */
  public static byte[] hexStringToArray(String s) {
    byte[] b = new byte[s.length() / 2];
    for (int i = 0; i < s.length() / 2; i++) {
      b[i] = (byte) (Integer.parseInt(s.substring(2 * i, 2 * i + 2), 16) & 0xFF);
    }
    return b;
  }

  /**
   * Convert a NamedObjectId to a pretty string for use in log messages etc. This gives a better
   * formatting than the default protobuf-generated toString.
   */
  public static String idToString(NamedObjectId id) {
    if (id == null) return "null";
    if (id.hasNamespace()) {
      return "'" + id.getName() + "' (namespace: '" + id.getNamespace() + "')";
    } else {
      return "'" + id.getName() + "' (no namespace)";
    }
  }

  /**
   * Convert a list of NamedObjectId to a pretty string for use in log messages etc. This gives a
   * better formatting than the default protobuf-generated toString.
   */
  public static String idListToString(List<NamedObjectId> idList) {
    if (idList == null) return "null";
    StringBuilder buf = new StringBuilder("[");
    boolean first = true;
    for (NamedObjectId id : idList) {
      if (first) {
        first = false;
      } else {
        buf.append(", ");
      }
      buf.append(idToString(id));
    }
    return buf.append("]").toString();
  }
}
Ejemplo n.º 24
0
 /**
  * Returns the largest power of two less than or equal to {@code x}. This is equivalent to {@code
  * BigInteger.valueOf(2).pow(log2(x, FLOOR))}.
  *
  * @throws IllegalArgumentException if {@code x <= 0}
  * @since 20.0
  */
 @Beta
 public static BigInteger floorPowerOfTwo(BigInteger x) {
   return BigInteger.ZERO.setBit(log2(x, RoundingMode.FLOOR));
 }
Ejemplo n.º 25
0
 /**
  * Returns the smallest power of two greater than or equal to {@code x}. This is equivalent to
  * {@code BigInteger.valueOf(2).pow(log2(x, CEILING))}.
  *
  * @throws IllegalArgumentException if {@code x <= 0}
  * @since 20.0
  */
 @Beta
 public static BigInteger ceilingPowerOfTwo(BigInteger x) {
   return BigInteger.ZERO.setBit(log2(x, RoundingMode.CEILING));
 }
Ejemplo n.º 26
0
 /**
  * Returns the absolute value of this {@link BigFraction}.
  *
  * @return the absolute value as a {@link BigFraction}.
  */
 public BigFraction abs() {
   return (BigInteger.ZERO.compareTo(numerator) <= 0) ? this : negate();
 }
Ejemplo n.º 27
0
 /**
  * Divide the value of this fraction by the passed <code>BigInteger</code>, ie "this * 1 / bg",
  * returning the result in reduced form.
  *
  * @param bg the <code>BigInteger</code> to divide by, must not be <code>null</code>.
  * @return a {@link BigFraction} instance with the resulting values.
  * @throws NullArgumentException if the {@code BigInteger} is {@code null}.
  * @throws ZeroException if the fraction to divide by is zero.
  */
 public BigFraction divide(final BigInteger bg) {
   if (BigInteger.ZERO.equals(bg)) {
     throw new ZeroException(LocalizedFormats.ZERO_DENOMINATOR);
   }
   return new BigFraction(numerator, denominator.multiply(bg));
 }
Ejemplo n.º 28
0
 /**
  * Divide the value of this fraction by the passed <code>BigInteger</code>, ie "this * 1 / bg",
  * returning the result in reduced form.
  *
  * @param bg the <code>BigInteger</code> to divide by, must not be <code>null</code>.
  * @return a {@link BigFraction} instance with the resulting values.
  * @throws NullPointerException if the <code>BigInteger</code> is <code>null</code>.
  * @throws ArithmeticException if the fraction to divide by is zero.
  */
 public BigFraction divide(final BigInteger bg) {
   if (BigInteger.ZERO.equals(bg)) {
     throw MathRuntimeException.createArithmeticException("denominator must be different from 0");
   }
   return new BigFraction(numerator, denominator.multiply(bg));
 }