java.nio.ByteBuffer#putInt ( )源码实例Demo

下面列出了java.nio.ByteBuffer#putInt ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: Game   文件: Tile.java
/**
 * Writes the Tile raw data into a ByteBuffer
 */
ByteBuffer pack() throws IOException {
	ByteBuffer out = ByteBuffer.allocate(10);

	out.put(groundElevation);
	out.put(groundTexture);
	out.put(groundOverlay);
	out.put(roofTexture);

	out.put(horizontalWall);
	out.put(verticalWall);
	out.putInt(diagonalWalls);

	out.flip();
	return out;
}
 
源代码2 项目: ignite   文件: DataPageIO.java
/**
 * @param buf Buffer.
 * @param cacheId Cache ID.
 * @param rowOff Row offset.
 * @param len Length.
 * @param prevLen Prev length.
 */
private void writeCacheIdFragment(ByteBuffer buf, int cacheId, int rowOff, int len, int prevLen) {
    if (cacheId == 0)
        return;

    int size = 4;

    if (size <= len)
        buf.putInt(cacheId);
    else {
        ByteBuffer cacheIdBuf = ByteBuffer.allocate(size);

        cacheIdBuf.order(buf.order());

        cacheIdBuf.putInt(cacheId);

        buf.put(cacheIdBuf.array(), rowOff - prevLen, len);
    }
}
 
源代码3 项目: thundernetwork   文件: PubkeyIPObject.java
@Override
public byte[] getData () {
    //TODO: Have some proper summary here..
    ByteBuffer byteBuffer = ByteBuffer.allocate(IP.length() + 4 + 4 + pubkey.length + signature.length);
    try {
        byteBuffer.put(IP.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    byteBuffer.putInt(port);
    byteBuffer.put(pubkey);
    byteBuffer.put(signature);
    byteBuffer.putInt(timestamp);
    return byteBuffer.array();
}
 
源代码4 项目: remoteyourcam-usb   文件: Command.java
protected void encodeCommand(ByteBuffer b, int code) {
    b.putInt(12);
    b.putShort((short) Type.Command);
    b.putShort((short) code);
    b.putInt(camera.nextTransactionId());
    if (AppConfig.LOG_PACKETS) {
        Log.i(TAG, "command packet for " + getClass().getSimpleName());
        PacketUtil.logHexdump(TAG, b.array(), 12);
    }
}
 
源代码5 项目: waltz   文件: SegmentFileHeader.java
void writeTo(ByteBuffer byteBuffer) throws IOException {
    byteBuffer.putInt(VERSION);
    byteBuffer.putLong(System.currentTimeMillis());
    byteBuffer.putLong(key.getMostSignificantBits());
    byteBuffer.putLong(key.getLeastSignificantBits());
    byteBuffer.putInt(partitionId);
    byteBuffer.putLong(firstTransactionId);
}
 
源代码6 项目: ripple-lib-java   文件: NTRUSignerPrng.java
/**
 * Returns <code>n</code> random bytes
 *
 * @param n number of bytes to return
 * @return the next <code>n</code> random bytes
 */
byte[] nextBytes(int n)
{
    ByteBuffer buf = ByteBuffer.allocate(n);

    while (buf.hasRemaining())
    {
        ByteBuffer cbuf = ByteBuffer.allocate(seed.length + 4);
        cbuf.put(seed);
        cbuf.putInt(counter);
        byte[] array = cbuf.array();
        byte[] hash = new byte[hashAlg.getDigestSize()];

        hashAlg.update(array, 0, array.length);

        hashAlg.doFinal(hash, 0);

        if (buf.remaining() < hash.length)
        {
            buf.put(hash, 0, buf.remaining());
        }
        else
        {
            buf.put(hash);
        }
        counter++;
    }

    return buf.array();
}
 
源代码7 项目: openrtb-doubleclick   文件: DoubleClickCrypto.java
/**
 * Decrypts data.
 *
 * @param cipherData {@code initVector || E(payload) || I(signature)}
 * @return {@code initVector || payload || I'(signature)}
 *     Where I'(signature) == I(signature) for success, different for failure
 */
public byte[] decrypt(byte[] cipherData) throws SignatureException {
  checkArgument(cipherData.length >= OVERHEAD_SIZE,
      "Invalid cipherData, %s bytes", cipherData.length);

  // workBytes := initVector || E(payload) || I(signature)
  byte[] workBytes = cipherData.clone();
  ByteBuffer workBuffer = ByteBuffer.wrap(workBytes);
  boolean success = false;

  try {
    // workBytes := initVector || payload || I(signature)
    xorPayloadToHmacPad(workBytes);
    // workBytes := initVector || payload || I'(signature)
    int confirmationSignature = hmacSignature(workBytes);
    int integritySignature = workBuffer.getInt(workBytes.length - SIGNATURE_SIZE);
    workBuffer.putInt(workBytes.length - SIGNATURE_SIZE, confirmationSignature);

    if (confirmationSignature != integritySignature) {
      throw new SignatureException("Signature mismatch: "
          + Integer.toHexString(confirmationSignature)
          + " vs " + Integer.toHexString(integritySignature));
    }

    if (logger.isDebugEnabled()) {
      logger.debug(dump("Decrypted", cipherData, workBytes));
    }

    success = true;
    return workBytes;
  } finally {
    if (!success && logger.isDebugEnabled()) {
      logger.debug(dump("Decrypted (failed)", cipherData, workBytes));
    }
  }
}
 
源代码8 项目: android-chunk-utils   文件: XmlAttribute.java
@Override
public byte[] toByteArray(boolean shrink) {
  ByteBuffer buffer = ByteBuffer.allocate(SIZE).order(ByteOrder.LITTLE_ENDIAN);
  buffer.putInt(namespaceIndex());
  buffer.putInt(nameIndex());
  buffer.putInt(rawValueIndex());
  buffer.put(typedValue().toByteArray(shrink));
  return buffer.array();
}
 
源代码9 项目: geowave   文件: DataIndexOnlyIT.java
public byte[] toBinary() {
  // ID can be set from the adapter so no need to persist
  final ByteBuffer buf = ByteBuffer.allocate(12);
  buf.putInt((int) time);
  buf.putFloat(lat);
  buf.putFloat(lon);
  return buf.array();
}
 
源代码10 项目: hadoop   文件: DataChecksum.java
/**
 * Calculate checksums for the given data.
 * 
 * The 'mark' of the ByteBuffer parameters may be modified by this function,
 * but the position is maintained.
 * 
 * @param data the DirectByteBuffer pointing to the data to checksum.
 * @param checksums the DirectByteBuffer into which checksums will be
 *                  stored. Enough space must be available in this
 *                  buffer to put the checksums.
 */
public void calculateChunkedSums(ByteBuffer data, ByteBuffer checksums) {
  if (type.size == 0) return;
  
  if (data.hasArray() && checksums.hasArray()) {
    calculateChunkedSums(data.array(), data.arrayOffset() + data.position(), data.remaining(),
        checksums.array(), checksums.arrayOffset() + checksums.position());
    return;
  }

  if (NativeCrc32.isAvailable()) {
    NativeCrc32.calculateChunkedSums(bytesPerChecksum, type.id,
        checksums, data);
    return;
  }
  
  data.mark();
  checksums.mark();
  try {
    byte[] buf = new byte[bytesPerChecksum];
    while (data.remaining() > 0) {
      int n = Math.min(data.remaining(), bytesPerChecksum);
      data.get(buf, 0, n);
      summer.reset();
      summer.update(buf, 0, n);
      checksums.putInt((int)summer.getValue());
    }
  } finally {
    data.reset();
    checksums.reset();
  }
}
 
源代码11 项目: JMPQ3   文件: AttributesFile.java
public byte[] buildFile() {
    ByteBuffer buffer = ByteBuffer.wrap(file);
    buffer.order(ByteOrder.LITTLE_ENDIAN);
    buffer.position(8);
    for(int crc : crc32) {
        buffer.putInt(crc);
    }
    for(long timestamp : timestamps) {
        buffer.putLong(timestamp);
    }
    return buffer.array();
}
 
源代码12 项目: HtmlUnit-Android   文件: DataView.java
/**
 * Sets the given signed 32-bit integer at the specified offset.
 * @param byteOffset the byte offset
 * @param value the value
 * @param littleEndian whether the value is stored in little- or big-endian format
 */
@JsxFunction
public void setInt32(final int byteOffset, final int value, final boolean littleEndian) {
    final ByteBuffer buff = ByteBuffer.wrap(getBuffer().getBytes());
    if (littleEndian) {
        buff.order(ByteOrder.LITTLE_ENDIAN);
    }
    buff.putInt(getByteOffset() + byteOffset, value);
}
 
源代码13 项目: buck   文件: StringPool.java
public static StringPool create(Iterable<String> strings) {
  List<String> stringsList = ImmutableList.copyOf(strings);
  int stringCount = stringsList.size();

  ByteBuffer stringOffsets = wrap(new byte[4 * stringCount]);
  ByteArrayOutputStream stringData = new ByteArrayOutputStream();

  byte[] encodedLength = new byte[4];
  ByteBuffer lengthBuf = wrap(encodedLength);
  for (int i = 0; i < stringsList.size(); i++) {
    lengthBuf.position(0);
    String value = stringsList.get(i);
    putEncodedLength(lengthBuf, value.length());
    ByteBuffer encoded = Charsets.UTF_8.encode(value);
    putEncodedLength(lengthBuf, encoded.limit());

    stringOffsets.putInt(i * 4, stringData.size());
    stringData.write(encodedLength, 0, lengthBuf.position());
    stringData.write(encoded.array(), encoded.arrayOffset(), encoded.limit());
    stringData.write(0);
  }

  // Pad to 4-byte boundary.
  lengthBuf.putInt(0, 0);
  stringData.write(encodedLength, 0, (4 - (stringData.size() % 4)) % 4);

  return new StringPool(
      stringCount,
      0,
      true,
      false,
      stringOffsets,
      wrap(new byte[0]),
      wrap(stringData.toByteArray()),
      wrap(new byte[0]));
}
 
源代码14 项目: jstorm   文件: PartialKeyGrouping.java
@Override
public List<Integer> chooseTasks(int taskId, List<Object> values) {
    List<Integer> boltIds = new ArrayList<>(1);
    if (values.size() > 0) {
        byte[] raw;
        if (fields != null) {
            List<Object> selectedFields = outFields.select(fields, values);
            ByteBuffer out = ByteBuffer.allocate(selectedFields.size() * 4);
            for (Object o : selectedFields) {
                if (o instanceof List) {
                    out.putInt(Arrays.deepHashCode(((List) o).toArray()));
                } else if (o instanceof Object[]) {
                    out.putInt(Arrays.deepHashCode((Object[]) o));
                } else if (o instanceof byte[]) {
                    out.putInt(Arrays.hashCode((byte[]) o));
                } else if (o instanceof short[]) {
                    out.putInt(Arrays.hashCode((short[]) o));
                } else if (o instanceof int[]) {
                    out.putInt(Arrays.hashCode((int[]) o));
                } else if (o instanceof long[]) {
                    out.putInt(Arrays.hashCode((long[]) o));
                } else if (o instanceof char[]) {
                    out.putInt(Arrays.hashCode((char[]) o));
                } else if (o instanceof float[]) {
                    out.putInt(Arrays.hashCode((float[]) o));
                } else if (o instanceof double[]) {
                    out.putInt(Arrays.hashCode((double[]) o));
                } else if (o instanceof boolean[]) {
                    out.putInt(Arrays.hashCode((boolean[]) o));
                } else if (o != null) {
                    out.putInt(o.hashCode());
                } else {
                    out.putInt(0);
                }
            }
            raw = out.array();
        } else {
            raw = values.get(0).toString().getBytes(); // assume key is the first field
        }

        int firstChoice = (int) (Math.abs(h1.hashBytes(raw).asLong()) % this.targetTasks.size());
        int secondChoice = (int) (Math.abs(h2.hashBytes(raw).asLong()) % this.targetTasks.size());
        int selected = targetTaskStats[firstChoice] > targetTaskStats[secondChoice] ? secondChoice : firstChoice;
        boltIds.add(targetTasks.get(selected));
        targetTaskStats[selected]++;
    }
    return boltIds;
}
 
源代码15 项目: incubator-hivemall   文件: SlimUDTF.java
private void recordTrainingInput(final int itemI,
        @Nonnull final Int2ObjectMap<Int2FloatMap> knnItems, final int numKNNItems)
        throws HiveException {
    ByteBuffer buf = this._inputBuf;
    NioStatefulSegment dst = this._fileIO;

    if (buf == null) {
        // invoke only at task node (initialize is also invoked in compilation)
        final File file;
        try {
            file = File.createTempFile("hivemall_slim", ".sgmt"); // to save KNN data
            file.deleteOnExit();
            if (!file.canWrite()) {
                throw new UDFArgumentException(
                    "Cannot write a temporary file: " + file.getAbsolutePath());
            }
        } catch (IOException ioe) {
            throw new UDFArgumentException(ioe);
        }

        this._inputBuf = buf = ByteBuffer.allocateDirect(8 * 1024 * 1024); // 8MB
        this._fileIO = dst = new NioStatefulSegment(file, false);
    }

    int recordBytes = SizeOf.INT + SizeOf.INT + SizeOf.INT * 2 * knnItems.size()
            + (SizeOf.INT + SizeOf.FLOAT) * numKNNItems;
    int requiredBytes = SizeOf.INT + recordBytes; // need to allocate space for "recordBytes" itself

    int remain = buf.remaining();
    if (remain < requiredBytes) {
        writeBuffer(buf, dst);
    }

    buf.putInt(recordBytes);
    buf.putInt(itemI);
    buf.putInt(knnItems.size());

    for (Int2ObjectMap.Entry<Int2FloatMap> e1 : Fastutil.fastIterable(knnItems)) {
        int user = e1.getIntKey();
        buf.putInt(user);

        Int2FloatMap ru = e1.getValue();
        buf.putInt(ru.size());
        for (Int2FloatMap.Entry e2 : Fastutil.fastIterable(ru)) {
            buf.putInt(e2.getIntKey());
            buf.putFloat(e2.getFloatValue());
        }
    }
}
 
源代码16 项目: akka-tutorial   文件: BitSet.java
public void toBinary(ByteBuffer buffer) {
	buffer.putInt(this.words.length);
	for (int i = 0; i < this.words.length; i++)
		buffer.putLong(this.words[i]);
}
 
@Override
public ColumnBinary toBinary(
    final ColumnBinaryMakerConfig commonConfig ,
    final ColumnBinaryMakerCustomConfigNode currentConfigNode ,
    final CompressResultNode compressResultNode ,
    final IColumn column ) throws IOException {
  ColumnBinaryMakerConfig currentConfig = commonConfig;
  if ( currentConfigNode != null ) {
    currentConfig = currentConfigNode.getCurrentConfig();
  }
  long[] valueArray = new long[column.size()];
  byte[] isNullArray = new byte[column.size()];

  Long min = Long.MAX_VALUE;
  Long max = Long.MIN_VALUE;
  int rowCount = 0;
  boolean hasNull = false;
  for ( int i = 0 ; i < column.size() ; i++ ) {
    ICell cell = column.get(i);
    PrimitiveObject primitiveObj = null;
    if ( cell.getType() == ColumnType.NULL ) {
      hasNull = true;
      isNullArray[i] = 1;
    } else {
      PrimitiveCell stringCell = (PrimitiveCell) cell;
      primitiveObj = stringCell.getRow();
      valueArray[rowCount] = primitiveObj.getLong();
      if ( 0 < min.compareTo( valueArray[rowCount] ) ) {
        min = Long.valueOf( valueArray[rowCount] );
      }
      if ( max.compareTo( valueArray[rowCount] ) < 0 ) {
        max = Long.valueOf( valueArray[rowCount] );
      }
      rowCount++;
    }
  }

  if ( ! hasNull && min.equals( max ) ) {
    return ConstantColumnBinaryMaker.createColumnBinary(
        createConstObjectFromNum( column.getColumnType() , min ) ,
        column.getColumnName() ,
        column.size() );
  }

  IBinaryMaker binaryMaker = chooseBinaryMaker( min.longValue() , max.longValue() );
  ByteOrder order = ByteOrder.nativeOrder();

  int nullBinaryLength = 0;
  if ( hasNull ) {
    nullBinaryLength = isNullArray.length;
  }
  int valueLength = binaryMaker.calcBinarySize( rowCount );

  byte[] binaryRaw = new byte[ nullBinaryLength + valueLength ];
  if ( hasNull ) {
    ByteBuffer compressBinaryBuffer = ByteBuffer.wrap( binaryRaw , 0 , nullBinaryLength );
    compressBinaryBuffer.put( isNullArray );
  }
  binaryMaker.create(
      valueArray , binaryRaw , nullBinaryLength , valueLength , order , rowCount );

  CompressResult compressResult = compressResultNode.getCompressResult(
      this.getClass().getName() ,
      "c0"  ,
      currentConfig.compressionPolicy ,
      currentConfig.allowedRatio );
  byte[] compressBinary = currentConfig.compressorClass.compress(
      binaryRaw , 0 , binaryRaw.length , compressResult );

  byte[] binary =
      new byte[ Long.BYTES * 2 + Byte.BYTES * 2 + Integer.BYTES + compressBinary.length ];

  byte byteOrderByte = order == ByteOrder.BIG_ENDIAN ? (byte)0 : (byte)1;

  ByteBuffer wrapBuffer = ByteBuffer.wrap( binary , 0 , binary.length );
  wrapBuffer.putLong( min );
  wrapBuffer.putLong( max );
  wrapBuffer.put( hasNull ? (byte)1 : (byte)0 );
  wrapBuffer.put( byteOrderByte );
  wrapBuffer.putInt( rowCount );
  wrapBuffer.put( compressBinary );

  return new ColumnBinary(
      this.getClass().getName() ,
      currentConfig.compressorClass.getClass().getName() ,
      column.getColumnName() ,
      column.getColumnType() ,
      column.size() ,
      binary.length ,
      getLogicalSize( rowCount , column.getColumnType() ) ,
      -1 ,
      binary ,
      0 ,
      binary.length ,
      null );
}
 
源代码18 项目: apkfile   文件: LibraryChunk.java
@Override
protected void writeHeader(ByteBuffer output) {
    super.writeHeader(output);
    output.putInt(entries.size());
}
 
/**
 * Update the central directory signature of a .jar.
 *
 * @param file          the file to process
 * @param searchPattern the search patter to use
 * @param badSkipBytes  the bad bytes skip table
 * @param newSig        the new signature
 * @param endSig        the expected signature
 * @throws IOException
 */
private static void updateJar(final File file, final byte[] searchPattern, final int[] badSkipBytes, final int newSig, final int endSig) throws IOException {
    final RandomAccessFile raf = new RandomAccessFile(file, "rw");
    try {
        final FileChannel channel = raf.getChannel();
        try {
            long pos = channel.size() - ENDLEN;
            final ScanContext context;
            if (newSig == CRIPPLED_ENDSIG) {
                context = new ScanContext(GOOD_ENDSIG_PATTERN, CRIPPLED_ENDSIG_PATTERN);
            } else if (newSig == GOOD_ENDSIG) {
                context = new ScanContext(CRIPPLED_ENDSIG_PATTERN, GOOD_ENDSIG_PATTERN);
            } else {
                context = null;
            }

            if (!validateEndRecord(file, channel, pos, endSig)) {
                pos = scanForEndSig(file, channel, context);
            }
            if (pos == -1) {
                if (context.state == State.NOT_FOUND) {
                    // Don't fail patching if we cannot validate a valid zip
                    PatchLogger.ROOT_LOGGER.cannotInvalidateZip(file.getAbsolutePath());
                }
                return;
            }
            // Update the central directory record
            channel.position(pos);
            final ByteBuffer buffer = ByteBuffer.allocate(4);
            buffer.order(ByteOrder.LITTLE_ENDIAN);
            buffer.putInt(newSig);
            buffer.flip();
            while (buffer.hasRemaining()) {
                channel.write(buffer);
            }
        } finally {
            safeClose(channel);
        }
    } finally {
        safeClose(raf);
    }
}
 
源代码20 项目: ignite   文件: TcpRestParserSelfTest.java
/**
 * Assembles raw packet without any logical checks.
 *
 * @param magic Header for packet.
 * @param opCode Operation code.
 * @param opaque Opaque value.
 * @param key Key data.
 * @param val Value data.
 * @param extras Extras data.
 * @return Byte buffer containing assembled packet.
 */
private ByteBuffer rawPacket(byte magic, byte opCode, byte[] opaque, @Nullable byte[] key, @Nullable byte[] val,
    @Nullable byte[] extras) {
    // 1k should be enough.
    ByteBuffer res = ByteBuffer.allocate(1024);

    res.put(magic);
    res.put(opCode);

    int keyLen = key == null ? 0 : key.length;
    int extrasLen = extras == null ? 0 : extras.length;
    int valLen = val == null ? 0 : val.length;

    res.putShort((short)keyLen);
    res.put((byte)extrasLen);

    // Data type is always 0.
    res.put((byte)0);

    // Reserved.
    res.putShort((short)0);

    // Total body.
    res.putInt(keyLen + extrasLen + valLen);

    // Opaque.
    res.put(opaque);

    // CAS
    res.putLong(0);

    if (extrasLen > 0)
        res.put(extras);

    if (keyLen > 0)
        res.put(key);

    if (valLen > 0)
        res.put(val);

    res.flip();

    return res;
}