Example #1
0
  public Object evaluate() throws EvaluationException {
    try {
      Number l = (Number) left().evaluate();
      Number r = (Number) right().evaluate();

      if (l instanceof Float || l instanceof Double || r instanceof Float || r instanceof Double) {
        String[] parameters = {
          Util.getMessage("EvaluationException.and"),
          left().value().getClass().getName(),
          right().value().getClass().getName()
        };
        throw new EvaluationException(Util.getMessage("EvaluationException.1", parameters));
      } else {
        // Arithmetic and (&)
        // daz        value (new Long (l.longValue () & r.longValue ()));
        BigInteger uL = (BigInteger) coerceToTarget((BigInteger) l);
        BigInteger uR = (BigInteger) coerceToTarget((BigInteger) r);
        value(uL.and(uR));
      }
    } catch (ClassCastException e) {
      String[] parameters = {
        Util.getMessage("EvaluationException.and"),
        left().value().getClass().getName(),
        right().value().getClass().getName()
      };
      throw new EvaluationException(Util.getMessage("EvaluationException.1", parameters));
    }
    return value();
  } // evaluate
 /** @tests java.math.BigInteger#and(java.math.BigInteger) */
 @TestTargetNew(
     level = TestLevel.COMPLETE,
     notes = "",
     method = "and",
     args = {java.math.BigInteger.class})
 public void test_andLjava_math_BigInteger() {
   for (BigInteger[] element : booleanPairs) {
     BigInteger i1 = element[0], i2 = element[1];
     BigInteger res = i1.and(i2);
     assertTrue("symmetry of and", res.equals(i2.and(i1)));
     int len = Math.max(i1.bitLength(), i2.bitLength()) + 66;
     for (int i = 0; i < len; i++) {
       assertTrue("and", (i1.testBit(i) && i2.testBit(i)) == res.testBit(i));
     }
   }
 }
Example #3
0
 public void testIsPowerOfTwo() {
   for (BigInteger x : ALL_BIGINTEGER_CANDIDATES) {
     // Checks for a single bit set.
     boolean expected = x.signum() > 0 & x.and(x.subtract(ONE)).equals(ZERO);
     assertEquals(expected, BigIntegerMath.isPowerOfTwo(x));
   }
 }
Example #4
0
 public static void main(String args[]) throws Exception {
   Scanner cin = new Scanner(System.in);
   BigInteger s, M;
   int p, i;
   while (cin.hasNext()) {
     p = cin.nextInt();
     s = BigInteger.valueOf(4);
     M = BigInteger.ONE;
     M = M.shiftLeft(p).subtract(BigInteger.ONE);
     for (i = 0; i < p - 2; ++i) {
       s = s.multiply(s).subtract(BigInteger.valueOf(2));
       while (s.bitLength() > p) {
         s = s.shiftRight(p).add(s.and(M));
       }
     }
     if (s.compareTo(BigInteger.ZERO) == 0 || s.compareTo(M) == 0) {
       System.out.println(0);
       continue;
     }
     String ans = "";
     while (s.compareTo(BigInteger.ZERO) > 0) {
       long buf = s.mod(BigInteger.valueOf(16)).longValue();
       ans += Integer.toHexString((int) buf);
       s = s.divide(BigInteger.valueOf(16));
     }
     for (i = ans.length() - 1; i >= 0; --i) System.out.print(ans.charAt(i));
     System.out.println();
   }
 }
  /**
   * Convert decimal to hexadecimal�iNo limit string length�j <br>
   * Return hexadecimal string (unsigned integer number string) from decimal(integer number) <br>
   * In case parameter is a minus number, return blank string <br>
   *
   * @param argStr decimal string
   * @return hexadecimal string
   */
  public static String chgHexString(String argStr) {

    // In case parameter is a minus number, return blank string
    if (argStr.charAt(0) == '-') {
      return "";
    }

    StringBuffer hexb = new StringBuffer();
    BigInteger bi = new BigInteger(argStr);
    int tempInt;
    BigInteger tempBi;

    // Convert each 4 bit, start from the end.
    for (int bitlength = bi.bitLength(); bitlength > 0; bitlength -= 4) {
      tempBi = bi.and(HEX_MASK);
      tempInt = tempBi.intValue();
      hexb.append(HEX_STR.charAt(tempInt));
      bi = bi.shiftRight(4);
    }
    // correction after converting
    int hexlength = hexb.length();
    if (hexlength == 0) {
      // In case value =0, put "00"
      hexb.append("00");
    } else if ((hexlength % 2) == 1) {
      // After converting, if result is a old number string, add "0" at
      // the end of string
      hexb.append("0");
    }

    // Reverse result string (because string was converted from the
    // 4-bit-end)
    return hexb.reverse().toString();
  }
Example #6
0
  private void calculate() throws UnknownHostException {

    ByteBuffer maskBuffer;
    int targetSize;
    if (inetAddress.getAddress().length == 4) {
      maskBuffer = ByteBuffer.allocate(4).putInt(-1);
      targetSize = 4;
    } else {
      maskBuffer = ByteBuffer.allocate(16).putLong(-1L).putLong(-1L);
      targetSize = 16;
    }

    BigInteger mask = (new BigInteger(1, maskBuffer.array())).not().shiftRight(prefixLength);

    ByteBuffer buffer = ByteBuffer.wrap(inetAddress.getAddress());
    BigInteger ipVal = new BigInteger(1, buffer.array());

    BigInteger startIp = ipVal.and(mask);
    BigInteger endIp = startIp.add(mask.not());

    byte[] startIpArr = toBytes(startIp.toByteArray(), targetSize);
    byte[] endIpArr = toBytes(endIp.toByteArray(), targetSize);

    this.startAddress = InetAddress.getByAddress(startIpArr);
    this.endAddress = InetAddress.getByAddress(endIpArr);
  }
  /**
   * Find the number in between the high and the low value with the most zeroes.
   *
   * @param value the lower bound for the number
   * @param highValue the upper bound for the nubmer
   * @return the value for the number with the most zeroes between the two bounds
   */
  private BigInteger maxZeroes(BigInteger value, BigInteger highValue) {
    // Find the highest bit that would be possible to add one to before
    // going over the high value.
    int i = highValue.xor(value).bitLength();
    int j;
    while (--i >= 0) {
      // If you hit a zero bit...
      if (!value.testBit(i)) {
        // ...change that bit to a 1.
        value = value.setBit(i);

        // Create a bit mask to compare with.
        byte[] comparatorBytes = value.toByteArray();
        Arrays.fill(comparatorBytes, (byte) 0xFF);
        BigInteger comparator = new BigInteger(comparatorBytes);
        comparator = comparator.shiftLeft(i);

        // And the value with the bit mask. Everything after the changed
        // bit will be cleared en masse. Way faster than clearing bits
        // individually.
        value = value.and(comparator);
        break;
      }
    }
    return value;
  }
  private static void verifyDifficulty(
      StoredBlock prevBlock, Block added, BigInteger calcDiff, NetworkParameters params) {
    if (calcDiff.compareTo(params.getMaxTarget()) > 0) {
      log.info("Difficulty hit proof of work limit: {}", calcDiff.toString(16));
      calcDiff = params.getMaxTarget();
    }

    int accuracyBytes = (int) (added.getDifficultyTarget() >>> 24) - 3;
    final BigInteger receivedDifficulty = added.getDifficultyTargetAsInteger();

    // The calculated difficulty is to a higher precision than received, so reduce here.
    final BigInteger mask = BigInteger.valueOf(0xFFFFFFL).shiftLeft(accuracyBytes * 8);
    calcDiff = calcDiff.and(mask);

    if (CoinDefinition.TEST_NETWORK_STANDARD.equals(params.getStandardNetworkId())) {
      if (calcDiff.compareTo(receivedDifficulty) != 0) {
        throw new VerificationException(
            "Network provided difficulty bits do not match what was calculated: "
                + receivedDifficulty.toString(16)
                + " vs "
                + calcDiff.toString(16));
      }
    } else {
      final int height = prevBlock.getHeight() + 1;
      if (height <= 68589) {
        long nBitsNext = added.getDifficultyTarget();

        long calcDiffBits = (accuracyBytes + 3) << 24;
        calcDiffBits |= calcDiff.shiftRight(accuracyBytes * 8).longValue();

        final double n1 = CommonUtils.convertBitsToDouble(calcDiffBits);
        final double n2 = CommonUtils.convertBitsToDouble(nBitsNext);

        if (Math.abs(n1 - n2) > n1 * 0.2) {
          throw new VerificationException(
              "Network provided difficulty bits do not match what was calculated: "
                  + receivedDifficulty.toString(16)
                  + " vs "
                  + calcDiff.toString(16));
        }
      } else {
        if (calcDiff.compareTo(receivedDifficulty) != 0) {
          throw new VerificationException(
              "Network provided difficulty bits do not match what was calculated: "
                  + receivedDifficulty.toString(16)
                  + " vs "
                  + calcDiff.toString(16));
        }
      }
    }
  }
Example #9
0
  public int hammingDistance(SimHash other) {

    BigInteger x = this.intSimHash.xor(other.intSimHash);
    int tot = 0;

    // 统计x中二进制位数为1的个数
    // 我们想想,一个二进制数减去1,那么,从最后那个1(包括那个1)后面的数字全都反了,对吧,然后,n&(n-1)就相当于把后面的数字清0,
    // 我们看n能做多少次这样的操作就OK了。

    while (x.signum() != 0) {
      tot += 1;
      x = x.and(x.subtract(new BigInteger("1")));
    }
    return tot;
  }
Example #10
0
  public BigInteger[] unmerge(BigInteger msg) {
    BigInteger max = new BigInteger("18446744073709551615");
    LinkedList<BigInteger> list = new LinkedList<BigInteger>();

    BigInteger message = new BigInteger(msg.toString());
    while (message.bitLength() > 0) {
      list.addFirst(message.and(max));
      message = message.shiftRight(64);
    }

    BigInteger[] output = new BigInteger[list.size()];
    Iterator<BigInteger> it = list.iterator();
    int i = 0;
    while (it.hasNext()) {
      output[i] = it.next();
      i++;
    }
    return output;
  }
Example #11
0
  public static void bitOps(int order) {
    int failCount1 = 0, failCount2 = 0, failCount3 = 0;

    for (int i = 0; i < size * 5; i++) {
      BigInteger x = fetchNumber(order);
      BigInteger y;

      /* Test setBit and clearBit (and testBit) */
      if (x.signum() < 0) {
        y = BigInteger.valueOf(-1);
        for (int j = 0; j < x.bitLength(); j++) if (!x.testBit(j)) y = y.clearBit(j);
      } else {
        y = BigInteger.ZERO;
        for (int j = 0; j < x.bitLength(); j++) if (x.testBit(j)) y = y.setBit(j);
      }
      if (!x.equals(y)) failCount1++;

      /* Test flipBit (and testBit) */
      y = BigInteger.valueOf(x.signum() < 0 ? -1 : 0);
      for (int j = 0; j < x.bitLength(); j++) if (x.signum() < 0 ^ x.testBit(j)) y = y.flipBit(j);
      if (!x.equals(y)) failCount2++;
    }
    report("clearBit/testBit", failCount1);
    report("flipBit/testBit", failCount2);

    for (int i = 0; i < size * 5; i++) {
      BigInteger x = fetchNumber(order);

      /* Test getLowestSetBit() */
      int k = x.getLowestSetBit();
      if (x.signum() == 0) {
        if (k != -1) failCount3++;
      } else {
        BigInteger z = x.and(x.negate());
        int j;
        for (j = 0; j < z.bitLength() && !z.testBit(j); j++) ;
        if (k != j) failCount3++;
      }
    }
    report("getLowestSetBit", failCount3);
  }
Example #12
0
 public BigInteger simHash() {
   // 定义特征向量/数组
   int[] v = new int[this.hashbits];
   // 1、将文本去掉格式后, 分词.
   StringTokenizer stringTokens = new StringTokenizer(this.tokens);
   while (stringTokens.hasMoreTokens()) {
     String temp = stringTokens.nextToken();
     // 2、将每一个分词hash为一组固定长度的数列.比如 64bit 的一个整数.
     BigInteger t = this.hash(temp);
     for (int i = 0; i < this.hashbits; i++) {
       BigInteger bitmask = new BigInteger("1").shiftLeft(i);
       // 3、建立一个长度为64的整数数组(假设要生成64位的数字指纹,也可以是其它数字),
       // 对每一个分词hash后的数列进行判断,如果是1000...1,那么数组的第一位和末尾一位加1,
       // 中间的62位减一,也就是说,逢1加1,逢0减1.一直到把所有的分词hash数列全部判断完毕.
       if (t.and(bitmask).signum() != 0) {
         // 这里是计算整个文档的所有特征的向量和
         // 这里实际使用中需要 +- 权重,而不是简单的 +1/-1,
         v[i] += 1;
       } else {
         v[i] -= 1;
       }
     }
   }
   BigInteger fingerprint = new BigInteger("0");
   StringBuffer simHashBuffer = new StringBuffer();
   for (int i = 0; i < this.hashbits; i++) {
     // 4、最后对数组进行判断,大于0的记为1,小于等于0的记为0,得到一个 64bit 的数字指纹/签名.
     if (v[i] >= 0) {
       fingerprint = fingerprint.add(new BigInteger("1").shiftLeft(i));
       simHashBuffer.append("1");
     } else {
       simHashBuffer.append("0");
     }
   }
   this.strSimHash = simHashBuffer.toString();
   // System.out.println(this.strSimHash + " length " + this.strSimHash.length());
   return fingerprint;
 }
Example #13
0
  public static void bitwise(int order) {

    /* Test identity x^y == x|y &~ x&y */
    int failCount = 0;
    for (int i = 0; i < size; i++) {
      BigInteger x = fetchNumber(order);
      BigInteger y = fetchNumber(order);
      BigInteger z = x.xor(y);
      BigInteger w = x.or(y).andNot(x.and(y));
      if (!z.equals(w)) failCount++;
    }
    report("Logic (^ | & ~)", failCount);

    /* Test identity x &~ y == ~(~x | y) */
    failCount = 0;
    for (int i = 0; i < size; i++) {
      BigInteger x = fetchNumber(order);
      BigInteger y = fetchNumber(order);
      BigInteger z = x.andNot(y);
      BigInteger w = x.not().or(y).not();
      if (!z.equals(w)) failCount++;
    }
    report("Logic (&~ | ~)", failCount);
  }
Example #14
0
 public static BigInteger LAnd(BigInteger x, BigInteger y) {
   return x.and(y);
 }
  /** Throws an exception if the blocks difficulty is not correct. */
  private void checkDifficultyTransitions(StoredBlock storedPrev, StoredBlock storedNext)
      throws BlockStoreException, VerificationException {
    Block prev = storedPrev.getHeader();
    Block next = storedNext.getHeader();
    // Is this supposed to be a difficulty transition point?
    if ((storedPrev.getHeight() + 1) % params.interval != 0) {
      // No ... so check the difficulty didn't actually change.
      if (next.getDifficultyTarget() != prev.getDifficultyTarget())
        throw new VerificationException(
            "Unexpected change in difficulty at height "
                + storedPrev.getHeight()
                + ": "
                + Long.toHexString(next.getDifficultyTarget())
                + " vs "
                + Long.toHexString(prev.getDifficultyTarget()));
      return;
    }

    // We need to find a block far back in the chain. It's OK that this is expensive because it only
    // occurs every
    // two weeks after the initial block chain download.
    long now = System.currentTimeMillis();
    StoredBlock cursor = blockStore.get(prev.getHash());
    for (int i = 0; i < params.interval - 1; i++) {
      if (cursor == null) {
        // This should never happen. If it does, it means we are following an incorrect or busted
        // chain.
        throw new VerificationException(
            "Difficulty transition point but we did not find a way back to the genesis block.");
      }
      cursor = blockStore.get(cursor.getHeader().getPrevBlockHash());
    }
    log.info("Difficulty transition traversal took {}msec", System.currentTimeMillis() - now);

    Block blockIntervalAgo = cursor.getHeader();
    int timespan = (int) (prev.getTime() - blockIntervalAgo.getTime());
    // Limit the adjustment step.
    if (timespan < params.targetTimespan / 4) timespan = params.targetTimespan / 4;
    if (timespan > params.targetTimespan * 4) timespan = params.targetTimespan * 4;

    BigInteger newDifficulty = Utils.decodeCompactBits(blockIntervalAgo.getDifficultyTarget());
    newDifficulty = newDifficulty.multiply(BigInteger.valueOf(timespan));
    newDifficulty = newDifficulty.divide(BigInteger.valueOf(params.targetTimespan));

    if (newDifficulty.compareTo(params.proofOfWorkLimit) > 0) {
      log.warn("Difficulty hit proof of work limit: {}", newDifficulty.toString(16));
      newDifficulty = params.proofOfWorkLimit;
    }

    int accuracyBytes = (int) (next.getDifficultyTarget() >>> 24) - 3;
    BigInteger receivedDifficulty = next.getDifficultyTargetAsInteger();

    // The calculated difficulty is to a higher precision than received, so reduce here.
    BigInteger mask = BigInteger.valueOf(0xFFFFFFL).shiftLeft(accuracyBytes * 8);
    newDifficulty = newDifficulty.and(mask);

    if (newDifficulty.compareTo(receivedDifficulty) != 0)
      throw new VerificationException(
          "Network provided difficulty bits do not match what was calculated: "
              + receivedDifficulty.toString(16)
              + " vs "
              + newDifficulty.toString(16));
  }