Java Code Examples for java.nio.ByteBuffer#putDouble()

The following examples show how to use java.nio.ByteBuffer#putDouble() . 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
Source File: PayloadTests.java    From packer-ng-plugin with Apache License 2.0 6 votes vote down vote up
public void testByteBuffer() throws IOException {
        byte[] string = "Hello".getBytes();
        ByteBuffer buf = ByteBuffer.allocate(1024);
        buf.order(ByteOrder.LITTLE_ENDIAN);
        buf.putInt(123);
        buf.putChar('z');
        buf.putShort((short) 2017);
        buf.putFloat(3.1415f);
        buf.put(string);
        buf.putLong(9876543210L);
        buf.putDouble(3.14159265);
        buf.put((byte) 5);
        buf.flip(); // important
//        TestUtils.showBuffer(buf);
        assertEquals(123, buf.getInt());
        assertEquals('z', buf.getChar());
        assertEquals(2017, buf.getShort());
        assertEquals(3.1415f, buf.getFloat());
        byte[] so = new byte[string.length];
        buf.get(so);
        assertTrue(TestUtils.sameBytes(string, so));
        assertEquals(9876543210L, buf.getLong());
        assertEquals(3.14159265, buf.getDouble());
        assertEquals((byte) 5, buf.get());
    }
 
Example 2
Source File: GeoObjectDimensionValues.java    From geowave with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] toBinary() {
  final ByteBuffer b =
      ByteBuffer.allocate(
          ((4 + values.length) * 8)
              + VarintUtils.unsignedIntByteLength(values.length)
              + VarintUtils.unsignedLongByteLength(count));
  VarintUtils.writeUnsignedLong(count, b);
  b.putDouble(x);
  b.putDouble(y);
  b.putDouble(z);
  b.putDouble(distance);
  VarintUtils.writeUnsignedInt(values.length, b);
  for (final double value : values) {
    b.putDouble(value);
  }
  return b.array();
}
 
Example 3
Source File: FloatDefinitionTest.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
@NonNull
private static BitBuffer create64BitFloatByteBuffer() {
    double[] data = new double[2];
    data[0] = 2.0f;
    data[1] = 3.14f;
    ByteBuffer byb = ByteBuffer.allocate(128);
    byb.order(ByteOrder.nativeOrder());
    byb.mark();
    byb.putDouble(data[0]);
    byb.putDouble(data[1]);
    byb.reset();
    BitBuffer bb = new BitBuffer(byb);
    return bb;
}
 
Example 4
Source File: MergingDigest.java    From t-digest with Apache License 2.0 5 votes vote down vote up
@Override
public void asBytes(ByteBuffer buf) {
    compress();
    buf.putInt(Encoding.VERBOSE_ENCODING.code);
    buf.putDouble(min);
    buf.putDouble(max);
    buf.putDouble(publicCompression);
    buf.putInt(lastUsedCell);
    for (int i = 0; i < lastUsedCell; i++) {
        buf.putDouble(weight[i]);
        buf.putDouble(mean[i]);
    }
}
 
Example 5
Source File: FloatDefinitionTest.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
@NonNull
private static BitBuffer create64BitNegativeFloatByteBuffer() {
    double[] data = new double[2];
    data[0] = -2.0f;
    data[1] = -3.14f;
    ByteBuffer byb = ByteBuffer.allocate(128);
    byb.order(ByteOrder.nativeOrder());
    byb.mark();
    byb.putDouble(data[0]);
    byb.putDouble(data[1]);
    byb.reset();
    BitBuffer bb = new BitBuffer(byb);
    return bb;
}
 
Example 6
Source File: DataEncoderHelper.java    From bboxdb with Apache License 2.0 5 votes vote down vote up
/** 
 * Convert a array of double values into a byte buffer
 * @param longValues
 * @return
 */
public static ByteBuffer doubleArrayToByteBuffer(final double doubleValues[]) {
	final ByteBuffer byteBuffer = ByteBuffer.allocate(DOUBLE_BYTES * doubleValues.length);
	byteBuffer.order(APPLICATION_BYTE_ORDER);
	
	for(int i = 0; i < doubleValues.length; i++) {
		byteBuffer.putDouble(doubleValues[i]);
	}
	
	return byteBuffer;
}
 
Example 7
Source File: Rasters.java    From tiff-java with MIT License 5 votes vote down vote up
/**
 * Writes sample into given buffer.
 *
 * @param buffer
 *            A buffer to write to. @note Make sure buffer position is set.
 * @param fieldType
 *            field type to be written.
 * @param value
 *            Actual value to write.
 */
private void writeSample(ByteBuffer buffer, FieldType fieldType,
		Number value) {
	switch (fieldType) {
	case BYTE:
	case SBYTE:
		buffer.put(value.byteValue());
		break;
	case SHORT:
	case SSHORT:
		buffer.putShort(value.shortValue());
		break;
	case LONG:
	case SLONG:
		buffer.putInt(value.intValue());
		break;
	case FLOAT:
		buffer.putFloat(value.floatValue());
		break;
	case DOUBLE:
		buffer.putDouble(value.doubleValue());
		break;
	default:
		throw new TiffException("Unsupported raster field type: "
				+ fieldType);
	}
}
 
Example 8
Source File: PrimitiveConstant.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void serialize(ByteBuffer buffer) {
    switch (getJavaKind()) {
        case Byte:
        case Boolean:
            buffer.put((byte) primitive);
            break;
        case Short:
            buffer.putShort((short) primitive);
            break;
        case Char:
            buffer.putChar((char) primitive);
            break;
        case Int:
            buffer.putInt(asInt());
            break;
        case Long:
            buffer.putLong(asLong());
            break;
        case Float:
            buffer.putFloat(asFloat());
            break;
        case Double:
            buffer.putDouble(asDouble());
            break;
        default:
            throw new IllegalArgumentException("unexpected kind " + getJavaKind());
    }
}
 
Example 9
Source File: DoublePacker.java    From twister2 with Apache License 2.0 4 votes vote down vote up
@Override
public ByteBuffer addToBuffer(ByteBuffer byteBuffer, Double data) {
  return byteBuffer.putDouble(data);
}
 
Example 10
Source File: IntFeature.java    From incubator-hivemall with Apache License 2.0 4 votes vote down vote up
@Override
public void writeTo(@Nonnull final ByteBuffer dst) {
    dst.putInt(index);
    dst.putShort(field);
    dst.putDouble(value);
}
 
Example 11
Source File: JRSUIConstants.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
public void putValueInBuffer(final ByteBuffer buffer) {
    buffer.putDouble(doubleValue);
}
 
Example 12
Source File: LogItem.java    From Cybernet-VPN with GNU General Public License v3.0 4 votes vote down vote up
public byte[] getMarschaledBytes() throws UnsupportedEncodingException, BufferOverflowException {
    ByteBuffer bb = ByteBuffer.allocate(16384);
    bb.put((byte) 0x0);               //version
    bb.putLong(logtime);              //8
    bb.putInt(mVerbosityLevel);      //4
    bb.putInt(mLevel.getInt());
    bb.putInt(mRessourceId);
    if (mMessage == null || mMessage.length() == 0) {
        bb.putInt(0);
    } else {
        marschalString(mMessage, bb);
    }
    if (mArgs == null || mArgs.length == 0) {
        bb.putInt(0);
    } else {
        bb.putInt(mArgs.length);
        for (Object o : mArgs) {
            if (o instanceof String) {
                bb.putChar('s');
                marschalString((String) o, bb);
            } else if (o instanceof Integer) {
                bb.putChar('i');
                bb.putInt((Integer) o);
            } else if (o instanceof Float) {
                bb.putChar('f');
                bb.putFloat((Float) o);
            } else if (o instanceof Double) {
                bb.putChar('d');
                bb.putDouble((Double) o);
            } else if (o instanceof Long) {
                bb.putChar('l');
                bb.putLong((Long) o);
            } else if (o == null) {
                bb.putChar('0');
            } else {
                VpnStatus.logDebug("Unknown object for LogItem marschaling " + o);
                bb.putChar('s');
                marschalString(o.toString(), bb);
            }
        }
    }
    int pos = bb.position();
    bb.rewind();
    return Arrays.copyOf(bb.array(), pos);
}
 
Example 13
Source File: ForcefieldKernelOpenCL.java    From OSPREY3 with GNU General Public License v2.0 4 votes vote down vote up
public ForcefieldKernelOpenCL(GpuQueue queue, BigForcefieldEnergy ffenergy)
throws IOException {
	super(queue, "forcefield.cl", "calc");
	
	/* OPTIMIZATION: this kernel uses lots and lots of registers, so maxing out the work group size is sub-optimal
		using a smaller group size works noticeably better!
		empirically, using 1/4 the max seems to make the difference between 11x speedups and 15x speedups
	
		times in us for (131k atom pairs, 11k atom pairs, 200 atom pairs) on 1000th run, 6000th run, and 100000th run respectively
			1024: 369, 44, 18 (max on my hardware)
			256: 272, 33, 15
			128: 257, 31, 14
			64: 293, 33, 13
			32: 411, 44, 12
		
		looks to have slight dependency on num atom pairs, but 128 looks like a good compromise for all sizes
	*/
	groupSize = 128;
	
	// init defaults
	workSize = 0;
	
	this.ffenergy = ffenergy;
	
	// allocate the buffers
	CLContext context = getQueue().getCLQueue().getContext();
	coords = context.createBuffer(ffenergy.getCoords(), CLMemory.Mem.READ_WRITE);
	atomFlags = context.createBuffer(ffenergy.getAtomFlags(), CLMemory.Mem.READ_ONLY);
	precomputed = context.createBuffer(ffenergy.getPrecomputed(), CLMemory.Mem.READ_ONLY);
	subsetTable = context.createIntBuffer(ffenergy.getFullSubset().getNumAtomPairs(), CLMemory.Mem.READ_ONLY);
	energies = context.createDoubleBuffer(getEnergySize(ffenergy.getFullSubset()), CLMemory.Mem.WRITE_ONLY);
	
	// IMPORTANT: rewind the buffers before uploading, otherwise we get garbage on the gpu
	atomFlags.getBuffer().rewind();
	precomputed.getBuffer().rewind();
	
	// upload static info
	uploadBufferAsync(atomFlags);
	uploadBufferAsync(precomputed);
	
	// make the args buffer
	args = context.createByteBuffer(40, CLMemory.Mem.READ_ONLY);
	ByteBuffer argsBuf = args.getBuffer();
	argsBuf.rewind();
	argsBuf.putInt(0); // set by setSubsetInternal()
	argsBuf.putInt(0); // 
	argsBuf.putDouble(ffenergy.getParams().coulombFactor);
	argsBuf.putDouble(ffenergy.getParams().scaledCoulombFactor);
	argsBuf.putDouble(ffenergy.getParams().solvationCutoff2);
	argsBuf.put((byte)(ffenergy.getParams().useDistDependentDielectric ? 1 : 0));
	argsBuf.put((byte)(ffenergy.getParams().useHElectrostatics ? 1 : 0));
	argsBuf.put((byte)(ffenergy.getParams().useHVdw ? 1 : 0));
	argsBuf.put((byte)0); // set by setSubsetInternal()
	argsBuf.put((byte)(ffenergy.getParams().useEEF1 ? 1 : 0));
	argsBuf.flip();
	
	// set the subset
	// NOTE: setting the subset uploads the args too
	subset = null;
	setSubsetInternal(ffenergy.getFullSubset());
	
	getCLKernel()
		.setArg(0, coords)
		.setArg(1, atomFlags)
		.setArg(2, precomputed)
		.setArg(3, subsetTable)
		.setArg(4, energies)
		.setArg(5, args)
		.setNullArg(6, groupSize*Double.BYTES);
}
 
Example 14
Source File: LogItem.java    From bitmask_android with GNU General Public License v3.0 4 votes vote down vote up
public byte[] getMarschaledBytes() throws UnsupportedEncodingException, BufferOverflowException {
    ByteBuffer bb = ByteBuffer.allocate(16384);


    bb.put((byte) 0x0);               //version
    bb.putLong(logtime);              //8
    bb.putInt(mVerbosityLevel);      //4
    bb.putInt(mLevel.getInt());
    bb.putInt(mRessourceId);
    if (mMessage == null || mMessage.length() == 0) {
        bb.putInt(0);
    } else {
        marschalString(mMessage, bb);
    }
    if (mArgs == null || mArgs.length == 0) {
        bb.putInt(0);
    } else {
        bb.putInt(mArgs.length);
        for (Object o : mArgs) {
            if (o instanceof String) {
                bb.putChar('s');
                marschalString((String) o, bb);
            } else if (o instanceof Integer) {
                bb.putChar('i');
                bb.putInt((Integer) o);
            } else if (o instanceof Float) {
                bb.putChar('f');
                bb.putFloat((Float) o);
            } else if (o instanceof Double) {
                bb.putChar('d');
                bb.putDouble((Double) o);
            } else if (o instanceof Long) {
                bb.putChar('l');
                bb.putLong((Long) o);
            } else if (o == null) {
                bb.putChar('0');
            } else {
                VpnStatus.logDebug("Unknown object for LogItem marschaling " + o);
                bb.putChar('s');
                marschalString(o.toString(), bb);
            }

        }
    }

    int pos = bb.position();
    bb.rewind();
    return Arrays.copyOf(bb.array(), pos);

}
 
Example 15
Source File: TMzI.java    From act with GNU General Public License v3.0 4 votes vote down vote up
static void writeToByteBuffer(ByteBuffer buffer, float time, double mz, float intensity) {
  buffer.putFloat(time);
  buffer.putDouble(mz);
  buffer.putFloat(intensity);
}
 
Example 16
Source File: Nc4Iosp.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void copy(StructureData sdata, StructureMembers.Member m, ByteBuffer bb) {
  DataType dtype = m.getDataType();
  if (m.isScalar()) {
    switch (dtype) {
      case FLOAT:
        bb.putFloat(sdata.getScalarFloat(m));
        break;
      case DOUBLE:
        bb.putDouble(sdata.getScalarDouble(m));
        break;
      case INT:
      case ENUM4:
        bb.putInt(sdata.getScalarInt(m));
        break;
      case SHORT:
      case ENUM2:
        bb.putShort(sdata.getScalarShort(m));
        break;
      case BYTE:
      case ENUM1:
        bb.put(sdata.getScalarByte(m));
        break;
      case CHAR:
        bb.put((byte) sdata.getScalarChar(m));
        break;
      case LONG:
        bb.putLong(sdata.getScalarLong(m));
        break;
      default:
        throw new IllegalStateException("scalar " + dtype);
        /*
         * case BOOLEAN:
         * break;
         * case SEQUENCE:
         * break;
         * case STRUCTURE:
         * break;
         * case OPAQUE:
         * break;
         */
    }
  } else {
    int n = m.getSize();
    switch (dtype) {
      case FLOAT:
        float[] fdata = sdata.getJavaArrayFloat(m);
        for (int i = 0; i < n; i++)
          bb.putFloat(fdata[i]);
        break;
      case DOUBLE:
        double[] ddata = sdata.getJavaArrayDouble(m);
        for (int i = 0; i < n; i++)
          bb.putDouble(ddata[i]);
        break;
      case INT:
      case ENUM4:
        int[] idata = sdata.getJavaArrayInt(m);
        for (int i = 0; i < n; i++)
          bb.putInt(idata[i]);
        break;
      case SHORT:
      case ENUM2:
        short[] shdata = sdata.getJavaArrayShort(m);
        for (int i = 0; i < n; i++)
          bb.putShort(shdata[i]);
        break;
      case BYTE:
      case ENUM1:
        byte[] bdata = sdata.getJavaArrayByte(m);
        for (int i = 0; i < n; i++)
          bb.put(bdata[i]);
        break;
      case CHAR:
        char[] cdata = sdata.getJavaArrayChar(m);
        bb.put(IospHelper.convertCharToByte(cdata));
        break;
      case LONG:
        long[] ldata = sdata.getJavaArrayLong(m);
        for (int i = 0; i < n; i++)
          bb.putLong(ldata[i]);
        break;
      default:
        throw new IllegalStateException("array " + dtype);
        /*
         * case BOOLEAN:
         * break;
         * case OPAQUE:
         * break;
         * case STRUCTURE:
         * break; //
         */
      case SEQUENCE:
        break; // skip
    }
  }
}
 
Example 17
Source File: EncodeGorillaTest.java    From gorilla-tsc with Apache License 2.0 4 votes vote down vote up
/**
 * Tests encoding of similar floats, see https://github.com/dgryski/go-tsz/issues/4 for more information.
 */
@Test
void testEncodeSimilarFloats() throws Exception {
    long now = LocalDateTime.of(2015, Month.MARCH, 02, 00, 00).toInstant(ZoneOffset.UTC).toEpochMilli();

    LongArrayOutput output = new LongArrayOutput();
    GorillaCompressor c = new GorillaCompressor(now, output);

    ByteBuffer bb = ByteBuffer.allocate(5 * 2*Long.BYTES);

    bb.putLong(now + 1);
    bb.putDouble(6.00065e+06);
    bb.putLong(now + 2);
    bb.putDouble(6.000656e+06);
    bb.putLong(now + 3);
    bb.putDouble(6.000657e+06);
    bb.putLong(now + 4);
    bb.putDouble(6.000659e+06);
    bb.putLong(now + 5);
    bb.putDouble(6.000661e+06);

    bb.flip();

    for(int j = 0; j < 5; j++) {
        c.addValue(bb.getLong(), bb.getDouble());
    }

    c.close();

    bb.flip();

    LongArrayInput input = new LongArrayInput(output.getLongArray());
    GorillaDecompressor d = new GorillaDecompressor(input);

    // Replace with stream once GorillaDecompressor supports it
    for(int i = 0; i < 5; i++) {
        Pair pair = d.readPair();
        assertEquals(bb.getLong(), pair.getTimestamp(), "Timestamp did not match");
        assertEquals(bb.getDouble(), pair.getDoubleValue(), "Value did not match");
    }
    assertNull(d.readPair());
}
 
Example 18
Source File: ByteBuffUtil.java    From jforgame with Apache License 2.0 4 votes vote down vote up
public static void writeDouble(ByteBuffer buf, double value) {
	buf.putDouble(value);
}
 
Example 19
Source File: Uspln.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Read the header
 *
 * @return true if okay
 * @throws IOException problem reading file
 */
private boolean readStroke() throws IOException {
  String line = raf.readLine();
  if (line == null) {
    nelems = numFlashes; // track this for next time
    return false;
  }
  if (pMAGIC.matcher(line).find() || pMAGIC_OLD.matcher(line).find()) {
    return readStroke();
  }

  // 2006-10-23T17:59:39,18.415434,-93.480526,-26.8,1 (original)
  // 2006-10-23T17:59:39,18.415434,-93.480526,-26.8,0.25,0.5,80 (extended)
  Stroke stroke = null;

  StringTokenizer stoker = new StringTokenizer(line, ",\r\n");
  try {
    while (stoker.hasMoreTokens()) {
      Date date = isoDateFormat.parse(stoker.nextToken());
      double lat = Double.parseDouble(stoker.nextToken());
      double lon = Double.parseDouble(stoker.nextToken());
      double amp = Double.parseDouble(stoker.nextToken());
      int nstrokes = 1;
      double axisMaj = Double.NaN;
      double axisMin = Double.NaN;
      int orient = 0;
      if (isExtended) {
        axisMaj = Double.parseDouble(stoker.nextToken());
        axisMin = Double.parseDouble(stoker.nextToken());
        orient = Integer.parseInt(stoker.nextToken());
      } else {
        nstrokes = Integer.parseInt(stoker.nextToken());
      }

      stroke = isExtended ? new Stroke(date, lat, lon, amp, axisMaj, axisMin, orient)
          : new Stroke(date, lat, lon, amp, nstrokes);
    }
  } catch (Exception e) {
    logger.error("bad header: {}", line.trim());
    return false;
  }

  if (stroke == null) {
    logger.error("bad header: {}", line.trim());
    return false;
  }

  byte[] data = new byte[sm.getStructureSize()];
  ByteBuffer bbdata = ByteBuffer.wrap(data);
  for (String mbrName : sm.getMemberNames()) {
    switch (mbrName) {
      case TIME:
        bbdata.putDouble(stroke.secs);
        break;
      case LAT:
        bbdata.putDouble(stroke.lat);
        break;
      case LON:
        bbdata.putDouble(stroke.lon);
        break;
      case SIGNAL:
        bbdata.putFloat((float) stroke.amp);
        break;
      case MULTIPLICITY:
        bbdata.putInt(stroke.n);
        break;
      case MAJOR_AXIS:
        bbdata.putFloat((float) stroke.axisMajor);
        break;
      case MINOR_AXIS:
        bbdata.putFloat((float) stroke.axisMinor);
        break;
      case ELLIPSE_ANGLE:
        bbdata.putInt(stroke.axisOrient);
        break;
    }
  }
  asbb = new ArrayStructureBB(sm, new int[] {1}, bbdata, 0);
  return true;
}
 
Example 20
Source File: Node.java    From bt with Apache License 2.0 2 votes vote down vote up
/**
 * Saves the routing table to a file
 *
 * @param file to save to
 * @throws IOException
 */
void saveTable(Path saveTo) throws IOException {
	// don't persist in test mode
	if(!Files.isDirectory(saveTo.getParent()))
		return;
	
	Key currentRootID = getRootID();
	
	// called in an uninitialized state, no point in overwriting the table
	if(currentRootID == null)
		return;
	
	ByteBuffer tableBuffer = AnonAllocator.allocate(50*1024*1024);
	
	
	Map<String,Object> tableMap = new TreeMap<>();

	RoutingTable table = routingTableCOW;
	
	Stream<Map<String, Object>> main = table.stream().map(RoutingTableEntry::getBucket).flatMap(b -> b.entriesStream().map(KBucketEntry::toBencoded));
	Stream<Map<String, Object>> replacements = table.stream().map(RoutingTableEntry::getBucket).flatMap(b -> b.replacementsStream().map(KBucketEntry::toBencoded));
	
	tableMap.put("mainEntries", main);
	tableMap.put("replacements", replacements);
	
	ByteBuffer doubleBuf = ByteBuffer.wrap(new byte[8]);
	doubleBuf.putDouble(0, dht.getEstimator().getRawDistanceEstimate());
	tableMap.put("log2estimate", doubleBuf);
	
	tableMap.put("timestamp", System.currentTimeMillis());
	tableMap.put("oldKey", currentRootID.getHash());
	
	new BEncoder().encodeInto(tableMap, tableBuffer);
	
	Path tempFile = Files.createTempFile(saveTo.getParent(), "saveTable", "tmp");
	
	try(SeekableByteChannel chan = Files.newByteChannel(tempFile, StandardOpenOption.WRITE)) {
		chan.write(tableBuffer);
		chan.close();
		Files.move(tempFile, saveTo, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
	};

}