List of usage examples for java.lang Double longBitsToDouble
@HotSpotIntrinsicCandidate public static native double longBitsToDouble(long bits);
From source file:com.nextgis.mobile.fragment.MapFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_map, container, false); mCurrentLocationOverlay = new CurrentLocationOverlay(mActivity, mMap); mCurrentLocationOverlay.setStandingMarker(R.mipmap.ic_location_standing); mCurrentLocationOverlay.setMovingMarker(R.mipmap.ic_location_moving); mCurrentLocationOverlay.setAutopanningEnabled(true); mCurrentTrackOverlay = new CurrentTrackOverlay(mActivity, mMap); mRulerOverlay = new RulerOverlay(mActivity, mMap); mUndoRedoOverlay = new UndoRedoOverlay(mActivity, mMap); mMap.addOverlay(mCurrentTrackOverlay); mMap.addOverlay(mCurrentLocationOverlay); mMap.addOverlay(mEditLayerOverlay);/* ww w.j a v a 2 s.c o m*/ mMap.addOverlay(mUndoRedoOverlay); mMap.addOverlay(mRulerOverlay); //search relative view of map, if not found - add it mMapRelativeLayout = (RelativeLayout) view.findViewById(R.id.maprl); if (mMapRelativeLayout != null) { mMapRelativeLayout.addView(mMap, 0, new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT)); } float mapZoom; try { mapZoom = mPreferences.getFloat(SettingsConstantsUI.KEY_PREF_ZOOM_LEVEL, mMap.getMinZoom()); } catch (ClassCastException e) { mapZoom = mMap.getMinZoom(); } double mapScrollX; double mapScrollY; try { mapScrollX = Double.longBitsToDouble(mPreferences.getLong(SettingsConstantsUI.KEY_PREF_SCROLL_X, 0)); mapScrollY = Double.longBitsToDouble(mPreferences.getLong(SettingsConstantsUI.KEY_PREF_SCROLL_Y, 0)); } catch (ClassCastException e) { mapScrollX = 0; mapScrollY = 0; } mMap.setZoomAndCenter(mapZoom, new GeoPoint(mapScrollX, mapScrollY)); mMainButton = view.findViewById(R.id.multiple_actions); mAddPointButton = (FloatingActionButton) view.findViewById(R.id.add_point_by_tap); mAddPointButton.setOnClickListener(this); View addCurrentLocation = view.findViewById(R.id.add_current_location); addCurrentLocation.setOnClickListener(this); mAddNewGeometry = (FloatingActionButton) view.findViewById(R.id.add_new_geometry); mAddNewGeometry.setOnClickListener(this); mRuler = (FloatingActionButton) view.findViewById(R.id.action_ruler); mRuler.setOnClickListener(this); View addGeometryByWalk = view.findViewById(R.id.add_geometry_by_walk); addGeometryByWalk.setOnClickListener(this); mivZoomIn = (FloatingActionButton) view.findViewById(R.id.action_zoom_in); mivZoomIn.setOnClickListener(this); mivZoomOut = (FloatingActionButton) view.findViewById(R.id.action_zoom_out); mivZoomOut.setOnClickListener(this); mStatusPanel = (FrameLayout) view.findViewById(R.id.fl_status_panel); mScaleRuler = (ImageView) view.findViewById(R.id.iv_ruler); mScaleRulerText = (TextView) view.findViewById(R.id.tv_ruler); mScaleRulerText.setText(getRulerText()); mScaleRulerLayout = (LinearLayout) view.findViewById(R.id.ll_ruler); drawScaleRuler(); return view; }
From source file:org.renjin.parser.NumericLiterals.java
/** * Finds the closest double-precision floating point number to the given decimal string, parsed by * {@link #parseDoubleDecimal(CharSequence, int, int, int, char)} above. * * <p>This implementation is based on OpenJDK's {@code com.sun.misc.FloatingDecimal.ASCIIToBinaryBuffer.doubleValue()}, * but included here nearly verbatim to avoid a dependency on an internal SDK class. The original code * is copyright 1996, 2013, Oracle and/or its affiliates and licensed under the GPL v2.</p></p> * * @param in the input string/* ww w . ja v a2 s .c o m*/ * @param sign the sign, -1 or +1, parsed above in {@link #parseDouble(CharSequence, int, int, char, boolean)} * @param startIndex the index at which to start parsing * @param endIndex the index, exclusive, at which to stop parsing * @param decimalPoint the decimal point character to use. Generally either '.' or ',' * @return the number as a {@code double}, or {@code NA} if the string is malformatted. */ public static double doubleValue(boolean isNegative, int decExponent, char[] digits, int nDigits) { int kDigits = Math.min(nDigits, MAX_DECIMAL_DIGITS + 1); // // convert the lead kDigits to a long integer. // // (special performance hack: start to do it using int) int iValue = (int) digits[0] - (int) '0'; int iDigits = Math.min(kDigits, INT_DECIMAL_DIGITS); for (int i = 1; i < iDigits; i++) { iValue = iValue * 10 + (int) digits[i] - (int) '0'; } long lValue = (long) iValue; for (int i = iDigits; i < kDigits; i++) { lValue = lValue * 10L + (long) ((int) digits[i] - (int) '0'); } double dValue = (double) lValue; int exp = decExponent - kDigits; // // lValue now contains a long integer with the value of // the first kDigits digits of the number. // dValue contains the (double) of the same. // if (nDigits <= MAX_DECIMAL_DIGITS) { // // possibly an easy case. // We know that the digits can be represented // exactly. And if the exponent isn't too outrageous, // the whole thing can be done with one operation, // thus one rounding error. // Note that all our constructors trim all leading and // trailing zeros, so simple values (including zero) // will always end up here // if (exp == 0 || dValue == 0.0) { return (isNegative) ? -dValue : dValue; // small floating integer } else if (exp >= 0) { if (exp <= MAX_SMALL_TEN) { // // Can get the answer with one operation, // thus one roundoff. // double rValue = dValue * SMALL_10_POW[exp]; return (isNegative) ? -rValue : rValue; } int slop = MAX_DECIMAL_DIGITS - kDigits; if (exp <= MAX_SMALL_TEN + slop) { // // We can multiply dValue by 10^(slop) // and it is still "small" and exact. // Then we can multiply by 10^(exp-slop) // with one rounding. // dValue *= SMALL_10_POW[slop]; double rValue = dValue * SMALL_10_POW[exp - slop]; return (isNegative) ? -rValue : rValue; } // // Else we have a hard case with a positive exp. // } else { if (exp >= -MAX_SMALL_TEN) { // // Can get the answer in one division. // double rValue = dValue / SMALL_10_POW[-exp]; return (isNegative) ? -rValue : rValue; } // // Else we have a hard case with a negative exp. // } } // // Harder cases: // The sum of digits plus exponent is greater than // what we think we can do with one error. // // Start by approximating the right answer by, // naively, scaling by powers of 10. // if (exp > 0) { if (decExponent > MAX_DECIMAL_EXPONENT + 1) { // // Lets face it. This is going to be // Infinity. Cut to the chase. // return (isNegative) ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY; } if ((exp & 15) != 0) { dValue *= SMALL_10_POW[exp & 15]; } if ((exp >>= 4) != 0) { int j; for (j = 0; exp > 1; j++, exp >>= 1) { if ((exp & 1) != 0) { dValue *= BIG_10_POW[j]; } } // // The reason for the weird exp > 1 condition // in the above loop was so that the last multiply // would get unrolled. We handle it here. // It could overflow. // double t = dValue * BIG_10_POW[j]; if (Double.isInfinite(t)) { // // It did overflow. // Look more closely at the result. // If the exponent is just one too large, // then use the maximum finite as our estimate // value. Else call the result infinity // and punt it. // ( I presume this could happen because // rounding forces the result here to be // an ULP or two larger than // Double.MAX_VALUE ). // t = dValue / 2.0; t *= BIG_10_POW[j]; if (Double.isInfinite(t)) { return (isNegative) ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY; } t = Double.MAX_VALUE; } dValue = t; } } else if (exp < 0) { exp = -exp; if (decExponent < MIN_DECIMAL_EXPONENT - 1) { // // Lets face it. This is going to be // zero. Cut to the chase. // return (isNegative) ? -0.0 : 0.0; } if ((exp & 15) != 0) { dValue /= SMALL_10_POW[exp & 15]; } if ((exp >>= 4) != 0) { int j; for (j = 0; exp > 1; j++, exp >>= 1) { if ((exp & 1) != 0) { dValue *= TINY_10_POW[j]; } } // // The reason for the weird exp > 1 condition // in the above loop was so that the last multiply // would get unrolled. We handle it here. // It could underflow. // double t = dValue * TINY_10_POW[j]; if (t == 0.0) { // // It did underflow. // Look more closely at the result. // If the exponent is just one too small, // then use the minimum finite as our estimate // value. Else call the result 0.0 // and punt it. // ( I presume this could happen because // rounding forces the result here to be // an ULP or two less than // Double.MIN_VALUE ). // t = dValue * 2.0; t *= TINY_10_POW[j]; if (t == 0.0) { return (isNegative) ? -0.0 : 0.0; } t = Double.MIN_VALUE; } dValue = t; } } // // dValue is now approximately the result. // The hard part is adjusting it, by comparison // with FDBigInteger arithmetic. // Formulate the EXACT big-number result as // bigD0 * 10^exp // if (nDigits > MAX_NDIGITS) { nDigits = MAX_NDIGITS + 1; digits[MAX_NDIGITS] = '1'; } FDBigInteger bigD0 = new FDBigInteger(lValue, digits, kDigits, nDigits); exp = decExponent - nDigits; long ieeeBits = Double.doubleToRawLongBits(dValue); // IEEE-754 bits of double candidate final int B5 = Math.max(0, -exp); // powers of 5 in bigB, value is not modified inside correctionLoop final int D5 = Math.max(0, exp); // powers of 5 in bigD, value is not modified inside correctionLoop bigD0 = bigD0.multByPow52(D5, 0); bigD0.makeImmutable(); // prevent bigD0 modification inside correctionLoop FDBigInteger bigD = null; int prevD2 = 0; correctionLoop: while (true) { // here ieeeBits can't be NaN, Infinity or zero int binexp = (int) (ieeeBits >>> EXP_SHIFT); long bigBbits = ieeeBits & SIGNIF_BIT_MASK; if (binexp > 0) { bigBbits |= FRACT_HOB; } else { // Normalize denormalized numbers. assert bigBbits != 0L : bigBbits; // doubleToBigInt(0.0) int leadingZeros = Long.numberOfLeadingZeros(bigBbits); int shift = leadingZeros - (63 - EXP_SHIFT); bigBbits <<= shift; binexp = 1 - shift; } binexp -= EXP_BIAS; int lowOrderZeros = Long.numberOfTrailingZeros(bigBbits); bigBbits >>>= lowOrderZeros; final int bigIntExp = binexp - EXP_SHIFT + lowOrderZeros; final int bigIntNBits = EXP_SHIFT + 1 - lowOrderZeros; // // Scale bigD, bigB appropriately for // big-integer operations. // Naively, we multiply by powers of ten // and powers of two. What we actually do // is keep track of the powers of 5 and // powers of 2 we would use, then factor out // common divisors before doing the work. // int B2 = B5; // powers of 2 in bigB int D2 = D5; // powers of 2 in bigD int Ulp2; // powers of 2 in halfUlp. if (bigIntExp >= 0) { B2 += bigIntExp; } else { D2 -= bigIntExp; } Ulp2 = B2; // shift bigB and bigD left by a number s. t. // halfUlp is still an integer. int hulpbias; if (binexp <= -EXP_BIAS) { // This is going to be a denormalized number // (if not actually zero). // half an ULP is at 2^-(DoubleConsts.EXP_BIAS+EXP_SHIFT+1) hulpbias = binexp + lowOrderZeros + EXP_BIAS; } else { hulpbias = 1 + lowOrderZeros; } B2 += hulpbias; D2 += hulpbias; // if there are common factors of 2, we might just as well // factor them out, as they add nothing useful. int common2 = Math.min(B2, Math.min(D2, Ulp2)); B2 -= common2; D2 -= common2; Ulp2 -= common2; // do multiplications by powers of 5 and 2 FDBigInteger bigB = FDBigInteger.valueOfMulPow52(bigBbits, B5, B2); if (bigD == null || prevD2 != D2) { bigD = bigD0.leftShift(D2); prevD2 = D2; } // // to recap: // bigB is the scaled-big-int version of our floating-point // candidate. // bigD is the scaled-big-int version of the exact value // as we understand it. // halfUlp is 1/2 an ulp of bigB, except for special cases // of exact powers of 2 // // the plan is to compare bigB with bigD, and if the difference // is less than halfUlp, then we're satisfied. Otherwise, // use the ratio of difference to halfUlp to calculate a fudge // factor to add to the floating value, then go 'round again. // FDBigInteger diff; int cmpResult; boolean overvalue; if ((cmpResult = bigB.cmp(bigD)) > 0) { overvalue = true; // our candidate is too big. diff = bigB.leftInplaceSub(bigD); // bigB is not user further - reuse if ((bigIntNBits == 1) && (bigIntExp > -EXP_BIAS + 1)) { // candidate is a normalized exact power of 2 and // is too big (larger than Double.MIN_NORMAL). We will be subtracting. // For our purposes, ulp is the ulp of the // next smaller range. Ulp2 -= 1; if (Ulp2 < 0) { // rats. Cannot de-scale ulp this far. // must scale diff in other direction. Ulp2 = 0; diff = diff.leftShift(1); } } } else if (cmpResult < 0) { overvalue = false; // our candidate is too small. diff = bigD.rightInplaceSub(bigB); // bigB is not user further - reuse } else { // the candidate is exactly right! // this happens with surprising frequency break correctionLoop; } cmpResult = diff.cmpPow52(B5, Ulp2); if ((cmpResult) < 0) { // difference is small. // this is close enough break correctionLoop; } else if (cmpResult == 0) { // difference is exactly half an ULP // round to some other value maybe, then finish if ((ieeeBits & 1) != 0) { // half ties to even ieeeBits += overvalue ? -1 : 1; // nextDown or nextUp } break correctionLoop; } else { // difference is non-trivial. // could scale addend by ratio of difference to // halfUlp here, if we bothered to compute that difference. // Most of the time ( I hope ) it is about 1 anyway. ieeeBits += overvalue ? -1 : 1; // nextDown or nextUp if (ieeeBits == 0 || ieeeBits == EXP_BIT_MASK) { // 0.0 or Double.POSITIVE_INFINITY break correctionLoop; // oops. Fell off end of range. } continue; // try again. } } if (isNegative) { ieeeBits |= SIGN_BIT_MASK; } return Double.longBitsToDouble(ieeeBits); }
From source file:it.unibo.alchemist.model.implementations.actions.SocialForceAgent.java
@Override public void execute() { // Retrieve the local neighborhood final Neighborhood<List<ILsaMolecule>> neigh = getLocalNeighborhood(); targetPositions = null;//from ww w.j av a 2s. c o m bestNode = null; // If a group doesn't exists if (groupId == 0) { // Execute only the minimum gradient value search minimumGradientSearch(neigh); } else { // If a group exist // If minimum gradient value search is selected if (getMinimumGradient) { // For each node in the neighborhood minimumGradientSearch(neigh); // If there aren't any minimum gradient node, return if (bestNode == null || bestNode.contains(ACTIVE)) { return; } releasepheromone(); } else { // If the maximum pheromone value search maximumpheromoneSearch(neigh); // If there aren't any minumum gradient node, return if (bestNode == null || bestNode.contains(ACTIVE)) { /* * TODO: the pedestrian may loop in here. This is a bug. */ return; } checkMaxpheromoneNodeDistance(); } } // If there aren't any minumum gradient node, return if (bestNode == null || bestNode.contains(ACTIVE)) { return; } if (targetPositions != null) { // Get target x and y coordinates final double x = targetPositions.getCartesianCoordinates()[0]; final double y = targetPositions.getCartesianCoordinates()[1]; double dx = 0; double dy = 0; double ax = 0; double ay = 0; // TARGET FORCE - Compute the target node attractive force // contribution final Position mypos = getCurrentPosition(); final double myx = mypos.getCartesianCoordinates()[0]; final double myy = mypos.getCartesianCoordinates()[1]; final double distancex = x - myx; final double distancey = y - myy; final double dist = env.getDistanceBetweenNodes(bestNode, getNode()); final double targetForceX = distancex / dist; // vector components final double targetForceY = distancey / dist; // DESIRED FORCE - Compute the desired force starting from the // target force and the agent's speed final Position desiredForce = new Continuous2DEuclidean(targetForceX * vmax, targetForceY * vmax); // SOCIAL FORCE - Compute neighbors pedestrians repulsive force // contribution final Position socialForce = computeInteractions(desiredForce, myx, myy); /* * DODGE FORCE - Compute the force contribution that makes * pedestrian turn rightor left in order to dodge other pedestrians */ final Position dodgeForce = computeDodgeForce(neigh, desiredForce, mypos); // OBSTACLE FORCE - Compute near obstacles repulsive force // contribution final Position obstacleForce = computeObstacleForce(myx, myy, mypos); // Compute acceleration components as a sum between all forces // acting on the agent ax = desiredForceFactor * desiredForce.getCartesianCoordinates()[0] + socialForceFactor * socialForce.getCartesianCoordinates()[0] + dodgeForceFactor * dodgeForce.getCartesianCoordinates()[0] + obstacleForceFactor * obstacleForce.getCartesianCoordinates()[0]; ay = desiredForceFactor * desiredForce.getCartesianCoordinates()[1] + socialForceFactor * socialForce.getCartesianCoordinates()[1] + dodgeForceFactor * dodgeForce.getCartesianCoordinates()[1] + obstacleForceFactor * obstacleForce.getCartesianCoordinates()[1]; // Compute new speed components vx = momentumFactor * vx + ax; vy = momentumFactor * vy + ay; // Check if new speed is greater than max speed, adjust it final double speed = Math.sqrt(vx * vx + vy * vy); if (speed > vmax) { vx = (vx / speed) * vmax; // compute the vector components vy = (vy / speed) * vmax; } // Compute displacement components dx = deltaT * vx; dy = deltaT * vy; // DIRECTION ADJUSTMENT /* * Check if both new displacement components aren't opposite to * previous displacement components.So an agent ignore those * displacement that lead him to make a step back. */ if ((Double.longBitsToDouble(Double.doubleToRawLongBits(dxOld) ^ Double.doubleToRawLongBits(dx))) < 0 && (Double.longBitsToDouble( Double.doubleToRawLongBits(dyOld) ^ Double.doubleToRawLongBits(dy))) < 0) { if (rs.nextDouble() > 1 - pejorativeMoveProbability) { dx = 0; dy = 0; } } else { // Compute the new direction components as a weighted average // between old and freshly computed direction components. dx = (dxOld * oldW + dx * newW) / (oldW + newW); dy = (dyOld * oldW + dy * newW) / (oldW + newW); } // Store new direction components for the next cycle dxOld = dx; dyOld = dy; // BODY-TO-BODY INTERACION ADJUSTMENT // For each node in the neighborhood for (final Node<List<ILsaMolecule>> node : neigh.getNeighbors()) { final ILsaNode n = (ILsaNode) node; // If the current node is a person if (n.getConcentration(PERSON).size() != 0) { final Position pos = env.getPosition(n); double xOther = 0, yOther = 0; // If the distance between me and the current person is // less than a certain range if (pos.getDistanceTo(mypos) < proximityDecelerationRange) { xOther = pos.getCartesianCoordinates()[0]; yOther = pos.getCartesianCoordinates()[1]; // If the current person is in front of me, so // decelerate if ((dx > 0 && xOther > myx) || (dx < 0 && xOther < myx)) { dx = dx * decelerationFactor; } if ((dy > 0 && yOther > myy) || (dy < 0 && yOther < myy)) { dy = dy * decelerationFactor; } } } } // STOPPING THE MOVEMENT AT THE DESTINATION // If the final target node is in line of sight if (stopAtTarget && targetInLineOfSight) { /* * If the displacement is too little means that the agent is * very near to the destination butcan't proceed because of the * presence of other pedestrians */ if (dx < minDisplacement && dx > -minDisplacement && dy < minDisplacement && dy > -minDisplacement) { minDisplacementCycleCount++; } // If the count of cycles in which the displacement is // negligible is greater than a certain threshold if (minDisplacementCycleCount > minDispCycTh) { // Don't move anymore dx = 0; dy = 0; } } // If displacement components are greater than zero, check if they // aren't over the limit dx = dx > 0 ? Math.min(LIMIT, dx) : Math.max(-LIMIT, dx); dy = dy > 0 ? Math.min(LIMIT, dy) : Math.max(-LIMIT, dy); // If displacement components are greater than zero perform a // movement final boolean moveH = dx > 0 || dx < 0; final boolean moveV = dy > 0 || dy < 0; if (moveH || moveV) { move(new Continuous2DEuclidean(moveH ? dx : 0, moveV ? dy : 0)); } } }
From source file:com.datatorrent.lib.appdata.gpo.GPOUtils.java
/** * This method deserializes a double from the given byte array from the given offset, * and increments the offset appropriately. * @param buffer The byte buffer to deserialize from. * @param offset The offset to deserialize from. * @return The deserialized double./* w w w. j av a 2 s. c o m*/ */ public static double deserializeDouble(byte[] buffer, MutableInt offset) { int offsetInt = offset.intValue(); long val = (((long) buffer[0 + offsetInt]) & 0xFFL) << 56 | ((((long) buffer[1 + offsetInt]) & 0xFFL) << 48) | ((((long) buffer[2 + offsetInt]) & 0xFFL) << 40) | ((((long) buffer[3 + offsetInt]) & 0xFFL) << 32) | ((((long) buffer[4 + offsetInt]) & 0xFFL) << 24) | ((((long) buffer[5 + offsetInt]) & 0xFFL) << 16) | ((((long) buffer[6 + offsetInt]) & 0xFFL) << 8) | (((long) buffer[7 + offsetInt]) & 0xFFL); offset.add(Type.DOUBLE.getByteSize()); return Double.longBitsToDouble(val); }
From source file:com.healthmarketscience.jackcess.Column.java
/** * Decodes a date value./*w ww . j av a2 s. com*/ */ private Date readDateValue(ByteBuffer buffer) { // seems access stores dates in the local timezone. guess you just hope // you read it in the same timezone in which it was written! long dateBits = buffer.getLong(); long time = fromDateDouble(Double.longBitsToDouble(dateBits)); return new DateExt(time, dateBits); }
From source file:org.freedesktop.dbus.Message.java
/** * Demarshall one value from a buffer.//w w w . jav a2s.c o m * * @param sigb * A buffer of the D-Bus signature. * @param buf * The buffer to demarshall from. * @param ofs * An array of two ints, the offset into the signature buffer * and the offset into the data buffer. These values will be * updated to the start of the next value ofter demarshalling. * @param contained * converts nested arrays to Lists * @return The demarshalled value. */ private Object extractone(byte[] sigb, byte[] buf, int[] ofs, boolean contained) throws DBusException { if (log.isTraceEnabled()) { log.trace("Extracting type: " + ((char) sigb[ofs[0]]) + " from offset " + ofs[1]); } Object rv = null; ofs[1] = align(ofs[1], sigb[ofs[0]]); switch (sigb[ofs[0]]) { case ArgumentType.BYTE: rv = buf[ofs[1]++]; break; case ArgumentType.UINT32: rv = new UInt32(demarshallint(buf, ofs[1], 4)); ofs[1] += 4; break; case ArgumentType.INT32: rv = (int) demarshallint(buf, ofs[1], 4); ofs[1] += 4; break; case ArgumentType.INT16: rv = (short) demarshallint(buf, ofs[1], 2); ofs[1] += 2; break; case ArgumentType.UINT16: rv = new UInt16((int) demarshallint(buf, ofs[1], 2)); ofs[1] += 2; break; case ArgumentType.INT64: rv = demarshallint(buf, ofs[1], 8); ofs[1] += 8; break; case ArgumentType.UINT64: long top; long bottom; if (this.big) { top = demarshallint(buf, ofs[1], 4); ofs[1] += 4; bottom = demarshallint(buf, ofs[1], 4); } else { bottom = demarshallint(buf, ofs[1], 4); ofs[1] += 4; top = demarshallint(buf, ofs[1], 4); } rv = new UInt64(top, bottom); ofs[1] += 4; break; case ArgumentType.DOUBLE: long l = demarshallint(buf, ofs[1], 8); ofs[1] += 8; rv = Double.longBitsToDouble(l); break; case ArgumentType.FLOAT: int rf = (int) demarshallint(buf, ofs[1], 4); ofs[1] += 4; rv = Float.intBitsToFloat(rf); break; case ArgumentType.BOOLEAN: rf = (int) demarshallint(buf, ofs[1], 4); ofs[1] += 4; rv = (1 == rf) ? Boolean.TRUE : Boolean.FALSE; break; case ArgumentType.ARRAY: long size = demarshallint(buf, ofs[1], 4); if (log.isTraceEnabled()) { log.trace("Reading array of size: " + size); } ofs[1] += 4; byte algn = (byte) getAlignment(sigb[++ofs[0]]); ofs[1] = align(ofs[1], sigb[ofs[0]]); int length = (int) (size / algn); if (length > AbstractConnection.MAX_ARRAY_LENGTH) throw new MarshallingException("Arrays must not exceed " + AbstractConnection.MAX_ARRAY_LENGTH); // optimise primatives switch (sigb[ofs[0]]) { case ArgumentType.BYTE: rv = new byte[length]; System.arraycopy(buf, ofs[1], rv, 0, length); ofs[1] += size; break; case ArgumentType.INT16: rv = new short[length]; for (int j = 0; j < length; j++, ofs[1] += algn) ((short[]) rv)[j] = (short) demarshallint(buf, ofs[1], algn); break; case ArgumentType.INT32: rv = new int[length]; for (int j = 0; j < length; j++, ofs[1] += algn) ((int[]) rv)[j] = (int) demarshallint(buf, ofs[1], algn); break; case ArgumentType.INT64: rv = new long[length]; for (int j = 0; j < length; j++, ofs[1] += algn) ((long[]) rv)[j] = demarshallint(buf, ofs[1], algn); break; case ArgumentType.BOOLEAN: rv = new boolean[length]; for (int j = 0; j < length; j++, ofs[1] += algn) ((boolean[]) rv)[j] = (1 == demarshallint(buf, ofs[1], algn)); break; case ArgumentType.FLOAT: rv = new float[length]; for (int j = 0; j < length; j++, ofs[1] += algn) ((float[]) rv)[j] = Float.intBitsToFloat((int) demarshallint(buf, ofs[1], algn)); break; case ArgumentType.DOUBLE: rv = new double[length]; for (int j = 0; j < length; j++, ofs[1] += algn) ((double[]) rv)[j] = Double.longBitsToDouble(demarshallint(buf, ofs[1], algn)); break; case ArgumentType.DICT_ENTRY1: if (0 == size) { // advance the type parser even on 0-size arrays. Vector<Type> temp = new Vector<>(); byte[] temp2 = new byte[sigb.length - ofs[0]]; System.arraycopy(sigb, ofs[0], temp2, 0, temp2.length); String temp3 = new String(temp2); // ofs[0] gets incremented anyway. Leave one character on the stack int temp4 = Marshalling.getJavaType(temp3, temp, 1) - 1; ofs[0] += temp4; if (log.isTraceEnabled()) { log.trace("Aligned type: " + temp3 + " " + temp4 + " " + ofs[0]); } } int ofssave = ofs[0]; long end = ofs[1] + size; Vector<Object[]> entries = new Vector<>(); while (ofs[1] < end) { ofs[0] = ofssave; entries.add((Object[]) extractone(sigb, buf, ofs, true)); } rv = new DBusMap<>(entries.toArray(new Object[0][])); break; default: if (0 == size) { // advance the type parser even on 0-size arrays. Vector<Type> temp = new Vector<>(); byte[] temp2 = new byte[sigb.length - ofs[0]]; System.arraycopy(sigb, ofs[0], temp2, 0, temp2.length); String temp3 = new String(temp2); // ofs[0] gets incremented anyway. Leave one character on the stack int temp4 = Marshalling.getJavaType(temp3, temp, 1) - 1; ofs[0] += temp4; if (log.isTraceEnabled()) { log.trace("Aligned type: " + temp3 + " " + temp4 + " " + ofs[0]); } } ofssave = ofs[0]; end = ofs[1] + size; Vector<Object> contents = new Vector<>(); while (ofs[1] < end) { ofs[0] = ofssave; contents.add(extractone(sigb, buf, ofs, true)); } rv = contents; } if (contained && !(rv instanceof List) && !(rv instanceof Map)) rv = ArrayFrob.listify(rv); break; case ArgumentType.STRUCT1: Vector<Object> contents = new Vector<>(); while (sigb[++ofs[0]] != ArgumentType.STRUCT2) contents.add(extractone(sigb, buf, ofs, true)); rv = contents.toArray(); break; case ArgumentType.DICT_ENTRY1: Object[] decontents = new Object[2]; if (log.isTraceEnabled()) { Hex h = new Hex(); log.trace( "Extracting Dict Entry (" + h.encode(Arrays.copyOfRange(sigb, ofs[0], sigb.length - ofs[0])) + ") from: " + h.encode(Arrays.copyOfRange(buf, ofs[1], buf.length - ofs[1]))); } ofs[0]++; decontents[0] = extractone(sigb, buf, ofs, true); ofs[0]++; decontents[1] = extractone(sigb, buf, ofs, true); ofs[0]++; rv = decontents; break; case ArgumentType.VARIANT: int[] newofs = new int[] { 0, ofs[1] }; String sig = (String) extract(ArgumentType.SIGNATURE_STRING, buf, newofs)[0]; newofs[0] = 0; rv = new Variant<>(extract(sig, buf, newofs)[0], sig); ofs[1] = newofs[1]; break; case ArgumentType.STRING: length = (int) demarshallint(buf, ofs[1], 4); ofs[1] += 4; try { rv = new String(buf, ofs[1], length, "UTF-8"); } catch (UnsupportedEncodingException UEe) { throw new DBusException("System does not support UTF-8 encoding", UEe); } ofs[1] += length + 1; break; case ArgumentType.OBJECT_PATH: length = (int) demarshallint(buf, ofs[1], 4); ofs[1] += 4; rv = new ObjectPath(getSource(), new String(buf, ofs[1], length)); ofs[1] += length + 1; break; case ArgumentType.SIGNATURE: length = (buf[ofs[1]++] & 0xFF); rv = new String(buf, ofs[1], length); ofs[1] += length + 1; break; default: throw new UnknownTypeCodeException(sigb[ofs[0]]); } if (log.isDebugEnabled()) { if (rv instanceof Object[]) log.trace("Extracted: " + Arrays.deepToString((Object[]) rv) + " (now at " + ofs[1] + ")"); else log.trace("Extracted: " + rv + " (now at " + ofs[1] + ")"); } return rv; }
From source file:com.healthmarketscience.jackcess.impl.DatabaseImpl.java
/** * Returns the password mask retrieved from the given header page and * format, or {@code null} if this format does not use a password mask. *///from w w w . java2s. co m static byte[] getPasswordMask(ByteBuffer buffer, JetFormat format) { // get extra password mask if necessary (the extra password mask is // generated from the database creation date stored in the header) int pwdMaskPos = format.OFFSET_HEADER_DATE; if (pwdMaskPos < 0) { return null; } buffer.position(pwdMaskPos); double dateVal = Double.longBitsToDouble(buffer.getLong()); byte[] pwdMask = new byte[4]; PageChannel.wrap(pwdMask).putInt((int) dateVal); return pwdMask; }
From source file:com.ricemap.spateDB.core.RTree.java
public static double fastPow(double a, double b) { final long tmp = (long) (9076650 * (a - 1) / (a + 1 + 4 * (Math.sqrt(a))) * b + 1072632447); return Double.longBitsToDouble(tmp << 32); }
From source file:com.healthmarketscience.jackcess.Database.java
/** * Returns the password mask retrieved from the given header page and * format, or {@code null} if this format does not use a password mask. *//*from ww w . j av a 2 s .c o m*/ static byte[] getPasswordMask(ByteBuffer buffer, JetFormat format) { // get extra password mask if necessary (the extra password mask is // generated from the database creation date stored in the header) int pwdMaskPos = format.OFFSET_HEADER_DATE; if (pwdMaskPos < 0) { return null; } buffer.position(pwdMaskPos); double dateVal = Double.longBitsToDouble(buffer.getLong()); byte[] pwdMask = new byte[4]; ByteBuffer.wrap(pwdMask).order(PageChannel.DEFAULT_BYTE_ORDER).putInt((int) dateVal); return pwdMask; }