类java.nio.ByteOrder源码实例Demo

下面列出了怎么用java.nio.ByteOrder的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: openjdk-jdk8u   文件: AudioFloatConverter.java
public float[] toFloatArray(byte[] in_buff, int in_offset,
        float[] out_buff, int out_offset, int out_len) {
    int in_len = out_len * 8;
    if (bytebuffer == null || bytebuffer.capacity() < in_len) {
        bytebuffer = ByteBuffer.allocate(in_len).order(
                ByteOrder.LITTLE_ENDIAN);
        floatbuffer = bytebuffer.asDoubleBuffer();
    }
    bytebuffer.position(0);
    floatbuffer.position(0);
    bytebuffer.put(in_buff, in_offset, in_len);
    if (double_buff == null
            || double_buff.length < out_len + out_offset)
        double_buff = new double[out_len + out_offset];
    floatbuffer.get(double_buff, out_offset, out_len);
    int out_offset_end = out_offset + out_len;
    for (int i = out_offset; i < out_offset_end; i++) {
        out_buff[i] = (float) double_buff[i];
    }
    return out_buff;
}
 
源代码2 项目: HoloKilo   文件: CubeRenderer.java
public CubeRenderer()
{
    cubeBuffer = ByteBuffer.allocateDirect(cube.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();
    cubeBuffer.put(cube).position(0);

    indexBuffer = ByteBuffer.allocateDirect(indeces.length * 4).order(ByteOrder.nativeOrder()).asShortBuffer();
    indexBuffer.put(indeces).position(0);

    texBuffer = ByteBuffer.allocateDirect(tex.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();
    texBuffer.put(tex).position(0);

    iProgId = loadProgram(strVShader, strFShader);
    iPosition = GLES20.glGetAttribLocation(iProgId, "a_position");
    iVPMatrix = GLES20.glGetUniformLocation(iProgId, "u_VPMatrix");
    iTexLoc = GLES20.glGetUniformLocation(iProgId, "u_texId");
    iTexCoords = GLES20.glGetAttribLocation(iProgId, "a_texCoords");
    iTexId = createCubeTexture();

    createVertexBuffers();
}
 
源代码3 项目: slick2d-maven   文件: AiffData.java
/**
 * Convert the audio bytes into the stream
 * 
 * @param format The audio format being decoded
 * @param audio_bytes The audio byts
 * @param two_bytes_data True if we using double byte data
 * @return The byte bufer of data
 */
private static ByteBuffer convertAudioBytes(AudioFormat format, byte[] audio_bytes, boolean two_bytes_data) {
	ByteBuffer dest = ByteBuffer.allocateDirect(audio_bytes.length);
	dest.order(ByteOrder.nativeOrder());
	ByteBuffer src = ByteBuffer.wrap(audio_bytes);
	src.order(ByteOrder.BIG_ENDIAN);
	if (two_bytes_data) {
		ShortBuffer dest_short = dest.asShortBuffer();
		ShortBuffer src_short = src.asShortBuffer();
		while (src_short.hasRemaining())
			dest_short.put(src_short.get());
	} else {
		while (src.hasRemaining()) {
			byte b = src.get();
			if (format.getEncoding() == Encoding.PCM_SIGNED) {
				b = (byte) (b + 127);
			}
			dest.put(b);
		}
	}
	dest.rewind();
	return dest;
}
 
源代码4 项目: grpc-nebula-java   文件: AltsFraming.java
/**
 * Completes the current frame, signaling that no further data is available to be passed to
 * readBytes and that the client requires writeBytes to start returning data. isComplete() is
 * guaranteed to return true after this call.
 */
void flush() throws GeneralSecurityException {
  if (isComplete) {
    return;
  }
  // Get the length of the complete frame.
  int frameLength = buffer.position() + getFrameSuffixLength();

  // Set the limit and move to the start.
  buffer.flip();

  // Advance the limit to allow a crypto suffix.
  buffer.limit(buffer.limit() + getFrameSuffixLength());

  // Write the data length and the message type.
  int dataLength = frameLength - FRAME_LENGTH_HEADER_SIZE;
  buffer.order(ByteOrder.LITTLE_ENDIAN);
  buffer.putInt(dataLength);
  buffer.putInt(MESSAGE_TYPE);

  // Move the position back to 0, the frame is ready.
  buffer.position(0);
  isComplete = true;
}
 
@Override
public void loadInMemoryStorage(
    final byte[] buffer ,
    final int start ,
    final int length ,
    final IMemoryAllocator allocator ,
    final byte[] isNullArray ,
    final int size ,
    final boolean hasNull ,
    final ByteOrder order ) throws IOException {
  IReadSupporter wrapBuffer =
      ByteBufferSupporterFactory.createReadSupporter( buffer , start , length , order );
  for ( int i = 0 ; i < size ; i++ ) {
    if ( ! hasNull || isNullArray[i] == 0 ) {
      allocator.setLong(
          i , NumberToBinaryUtils.getUnsignedShortToLong( wrapBuffer.getShort() ) + min );
    } else {
      allocator.setNull( i );
    }
  }
}
 
源代码6 项目: netty-4.1.22   文件: Base64Test.java
private static void testEncodeDecode(int size, ByteOrder order) {
    byte[] bytes = new byte[size];
    PlatformDependent.threadLocalRandom().nextBytes(bytes);

    ByteBuf src = Unpooled.wrappedBuffer(bytes).order(order);
    ByteBuf encoded = Base64.encode(src);
    ByteBuf decoded = Base64.decode(encoded);
    ByteBuf expectedBuf = Unpooled.wrappedBuffer(bytes);
    try {
        assertEquals(StringUtil.NEWLINE + "expected: " + ByteBufUtil.hexDump(expectedBuf) +
                     StringUtil.NEWLINE + "actual--: " + ByteBufUtil.hexDump(decoded), expectedBuf, decoded);
    } finally {
        src.release();
        encoded.release();
        decoded.release();
        expectedBuf.release();
    }
}
 
源代码7 项目: conga   文件: Exchange.java
private Exchange(Builder builder) {
  this.host = builder.host;
  this.port = builder.port;
  this.contextPath = builder.contextPath;
  // Jetty uses big-endian buffers for receiving but converts them to byte[]
  this.inboundRingBuffer = new RingBufferSupplier(incomingMessageConsumer, 1024,
      ByteOrder.nativeOrder(), 64, Executors.defaultThreadFactory());
  MessageProvider messageProvider = provider(builder.encoding);
  encodingType = messageProvider.encodingType();
  this.requestMessageFactory = messageProvider.getRequestMessageFactory();
  MutableResponseMessageFactory responseMessageFactory =
      messageProvider.getMutableResponseMessageFactory(outboundBufferSupplier);
  this.matchEngine = new MatchEngine(responseMessageFactory);
  this.sessions = new ServerSessions(new ServerSessionFactory(messageProvider,
      sessionMessageConsumer, timer, executor, builder.heartbeatInterval));
  Path outputPath = FileSystems.getDefault().getPath(builder.outputPath);
  this.inboundLogWriter = new MessageLogWriter(outputPath.resolve("inbound.log"), false);
  this.outboundLogWriter = new MessageLogWriter(outputPath.resolve("outbound.log"), false);
  this.keyStorePath = builder.keyStorePath;
  this.keyStorePassword = builder.keyStorePassword;
}
 
源代码8 项目: TelePlus-Android   文件: SonicAudioProcessor.java
@Override
public void queueInput(ByteBuffer inputBuffer) {
  Assertions.checkState(sonic != null);
  if (inputBuffer.hasRemaining()) {
    ShortBuffer shortBuffer = inputBuffer.asShortBuffer();
    int inputSize = inputBuffer.remaining();
    inputBytes += inputSize;
    sonic.queueInput(shortBuffer);
    inputBuffer.position(inputBuffer.position() + inputSize);
  }
  int outputSize = sonic.getFramesAvailable() * channelCount * 2;
  if (outputSize > 0) {
    if (buffer.capacity() < outputSize) {
      buffer = ByteBuffer.allocateDirect(outputSize).order(ByteOrder.nativeOrder());
      shortBuffer = buffer.asShortBuffer();
    } else {
      buffer.clear();
      shortBuffer.clear();
    }
    sonic.getOutput(shortBuffer);
    outputBytes += outputSize;
    buffer.limit(outputSize);
    outputBuffer = buffer;
  }
}
 
源代码9 项目: amidst   文件: LocalMinecraftInterface.java
private static long makeSeedForBiomeZoomer(long seed) throws MinecraftInterfaceException {
	try {
		MessageDigest digest = MessageDigest.getInstance("SHA-256");
		ByteBuffer buf = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN);
		buf.putLong(seed);
		byte[] bytes = digest.digest(buf.array());

		long result = 0;
		for (int i = 0; i < 8; i++) {
			result |= (bytes[i] & 0xffL) << (i*8L);
		}
		return result;
	} catch (NoSuchAlgorithmException e) {
		throw new MinecraftInterfaceException("unable to hash seed", e);
	}
}
 
源代码10 项目: MikuMikuStudio   文件: BufferUtil.java
private static ByteBuffer createByteBufferFile(int size) {
    try {
        if (tmpDir != null && logger.isLoggable(Level.INFO)) {
            logger.log(Level.INFO, "tmpDir = {0}", tmpDir.getAbsoluteFile());
        }
        File tmpFile = File.createTempFile("pmd","tmp", tmpDir);
        if (logger.isLoggable(Level.INFO)) {
            logger.log(Level.INFO, "tmpFile = {0}", tmpFile.getAbsoluteFile());
        }
        RandomAccessFile os = new RandomAccessFile(tmpFile, "rw");
        os.seek(size);
        os.write(0);
        FileChannel ch = os.getChannel();
        MappedByteBuffer  bb = ch.map(MapMode.READ_WRITE, 0, size);
        os.close();
        ch.close();
        tmpFile.delete();
        bb.order(ByteOrder.nativeOrder());
        return bb;
    } catch(IOException ex) {
        throw new RuntimeException(ex);
    }
}
 
源代码11 项目: RxCentralBle   文件: CoreParsedAdvertisement.java
public CoreParsedAdvertisement(byte[] rawAdData) {
  this.rawAdData = rawAdData;

  ByteBuffer byteBuffer = ByteBuffer.wrap(rawAdData).order(ByteOrder.LITTLE_ENDIAN);
  try {
    while (byteBuffer.hasRemaining()) {
      int length = byteBuffer.get() & 0xFF;
      if (length <= byteBuffer.remaining()) {
        int dataType = byteBuffer.get() & 0xFF;
        parseAdData(dataType, length - 1, byteBuffer);
      }
    }
  } catch (Exception e) {
    // Ignore exceptions; further data will not be parsed.
  }
}
 
源代码12 项目: flink   文件: AbstractByteBufTest.java
private void testMediumConsistentWithByteBuffer(boolean direct, boolean testBigEndian) {
    for (int i = 0; i < JAVA_BYTEBUFFER_CONSISTENCY_ITERATIONS; ++i) {
        ByteBuffer javaBuffer = direct ? ByteBuffer.allocateDirect(buffer.capacity())
                                       : ByteBuffer.allocate(buffer.capacity());
        if (!testBigEndian) {
            javaBuffer = javaBuffer.order(ByteOrder.LITTLE_ENDIAN);
        }

        int expected = random.nextInt() & 0x00FFFFFF;
        javaBuffer.putInt(expected);

        final int bufferIndex = buffer.capacity() - 3;
        if (testBigEndian) {
            buffer.setMedium(bufferIndex, expected);
        } else {
            buffer.setMediumLE(bufferIndex, expected);
        }
        javaBuffer.flip();

        int javaActual = javaBuffer.getInt();
        assertEquals(expected, javaActual);
        assertEquals(javaActual, testBigEndian ? buffer.getUnsignedMedium(bufferIndex)
                                               : buffer.getUnsignedMediumLE(bufferIndex));
    }
}
 
源代码13 项目: android_9.0.0_r45   文件: SurfaceTextureRenderer.java
private void configureEGLPbufferSurfaces(Collection<EGLSurfaceHolder> surfaces) {
    if (surfaces == null || surfaces.size() == 0) {
        throw new IllegalStateException("No Surfaces were provided to draw to");
    }

    int maxLength = 0;
    for (EGLSurfaceHolder holder : surfaces) {
        int length = holder.width * holder.height;
        // Find max surface size, ensure PBuffer can hold this many pixels
        maxLength = (length > maxLength) ? length : maxLength;
        int[] surfaceAttribs = {
                EGL14.EGL_WIDTH, holder.width,
                EGL14.EGL_HEIGHT, holder.height,
                EGL14.EGL_NONE
        };
        holder.eglSurface =
                EGL14.eglCreatePbufferSurface(mEGLDisplay, mConfigs, surfaceAttribs, 0);
        checkEglError("eglCreatePbufferSurface");
    }
    mPBufferPixels = ByteBuffer.allocateDirect(maxLength * PBUFFER_PIXEL_BYTES)
            .order(ByteOrder.nativeOrder());
}
 
源代码14 项目: tracecompass   文件: EventHeaderDeclarationTest.java
/**
 * Test an compact large header
 *
 * @throws CTFException
 *             if {@link BitBuffer} is null
 */
@Test
public void testLargeCompact() throws CTFException {
    ByteBuffer buffer = ByteBuffer.allocate(16);
    buffer.putShort((short) ID);
    buffer.putInt(TIMESTAMP);
    byte[] validLarge1 = buffer.array();

    EventHeaderLargeDeclaration decl = EventHeaderLargeDeclaration.getEventHeader(ByteOrder.BIG_ENDIAN);
    final ByteBuffer input = ByteBuffer.wrap(validLarge1);
    assertNotNull(input);
    EventHeaderDefinition def = decl.createDefinition(null, "bla", new BitBuffer(input));
    assertNotNull(def);
    assertEquals(ID, def.getId());
    assertEquals(TIMESTAMP, def.getTimestamp());
    assertEquals(ID, ((IntegerDefinition) def.getDefinition("id")).getValue());
    assertEquals(TIMESTAMP, ((IntegerDefinition) def.getDefinition("timestamp")).getValue());
}
 
源代码15 项目: jpexs-decompiler   文件: AbstractAVIStream.java
/**
 * Creates a new DataChunk at the current position of the
 * ImageOutputStream.
 *
 * @param chunkType The chunkType of the chunk.
 */
public FixedSizeDataChunk(int chunkType, long fixedSize) throws IOException {
    super(chunkType);
    this.fixedSize = fixedSize;
        out.setByteOrder(ByteOrder.BIG_ENDIAN);
    out.writeInt(chunkType);
        out.setByteOrder(ByteOrder.LITTLE_ENDIAN);
    out.writeInt((int) fixedSize);

    // Fill fixed size with nulls
    byte[] buf = new byte[(int) Math.min(512, fixedSize)];
    long written = 0;
    while (written < fixedSize) {
        out.write(buf, 0, (int) Math.min(buf.length, fixedSize - written));
        written += Math.min(buf.length, fixedSize - written);
    }
    if (fixedSize % 2 == 1) {
        out.writeByte(0); // write pad byte
    }
    seekToStartOfData();
}
 
private void setColors(int[] faceColors) {
    colors = new float[options * 4 * faceColors.length];
    int wOffset = 0;
    for (int faceColor : faceColors) {
        float[] color = hexToRGBA(faceColor);
        for(int j = 0; j < 4; j++) {
            colors[wOffset++] = color[0];
            colors[wOffset++] = color[1];
            colors[wOffset++] = color[2];
            colors[wOffset++] = color[3];
        }
    }
    ByteBuffer cbb = ByteBuffer.allocateDirect(colors.length * (Float.SIZE / 8));
    cbb.order(ByteOrder.nativeOrder());

    colorBuffer = cbb.asFloatBuffer();
    colorBuffer.put(colors);
    colorBuffer.position(0);
}
 
源代码17 项目: picard   文件: BclReader.java
private static long getNumberOfClusters(final String filePath, final InputStream inputStream) {
    final byte[] header = new byte[HEADER_SIZE];

    try {
        final int headerBytesRead = inputStream.read(header);
        if (headerBytesRead != HEADER_SIZE) {
            throw new PicardException("Malformed file, expected header of size " + HEADER_SIZE + " but received " + headerBytesRead);
        }
    } catch (final IOException ioe) {
        throw new PicardException("Unable to read header for file (" + filePath + ")", ioe);
    }

    final ByteBuffer headerBuf = ByteBuffer.wrap(header);
    headerBuf.order(ByteOrder.LITTLE_ENDIAN);
    return UnsignedTypeUtil.uIntToLong(headerBuf.getInt());
}
 
源代码18 项目: simplemagic   文件: FloatTypeTest.java
@Test
public void testBigEndian() throws IOException {
	String magic = "0 befloat >86400000000000 match";

	ByteBuffer bb = ByteBuffer.allocate(4);
	bb.order(ByteOrder.BIG_ENDIAN);
	bb.putFloat(Float.parseFloat("87200000000000"));
	bb.flip();
	byte[] bytes = bb.array();
	testOutput(magic, bytes, "match");

	bb = ByteBuffer.allocate(4);
	bb.order(ByteOrder.BIG_ENDIAN);
	bb.putFloat(Float.parseFloat("8.2e+13"));
	bb.flip();
	bytes = bb.array();
	testOutput(magic, bytes, null);
}
 
源代码19 项目: hypergraphdb   文件: DirectBuffer.java
public double getDouble(final int index, final ByteOrder byteOrder)
{
	boundsCheck(index, SIZE_OF_DOUBLE);

	if (NATIVE_BYTE_ORDER != byteOrder)
	{
		final long bits = UNSAFE.getLong(byteArray, addressOffset + index);
		return Double.longBitsToDouble(Long.reverseBytes(bits));
	}
	else
	{
		return UNSAFE.getDouble(byteArray, addressOffset + index);
	}
}
 
源代码20 项目: MeteoInfo   文件: StructureDataDeep.java
/**
 * Make deep copy from a StructureData to a ArrayStructureBB whose data is contained in a ByteBuffer
 * @param sdata    original ArrayStructure
 * @param sm       the StructureData members. a reference is kept to this object
 * @param bo       Byte Order of the ByteBuffer
 * @return ArrayStructureBB with all data self contained
 */
static public ArrayStructureBB copyToArrayBB(StructureData sdata, StructureMembers sm, ByteOrder bo) {
  int size = sm.getStructureSize();
  ByteBuffer bb = ByteBuffer.allocate(size); // default is big endian
  bb.order(bo);
  ArrayStructureBB abb = new ArrayStructureBB(sm, new int[]{1}, bb, 0);
  ArrayStructureBB.setOffsets(sm);
  copyToArrayBB(sdata, abb);
  return abb;
}
 
@Override
public void create( final List<byte[]> objList , final byte[] buffer , final int start , final int length , final ByteOrder order ) throws IOException{
  IWriteSupporter wrapBuffer = ByteBufferSupporterFactory.createWriteSupporter( buffer , start , length , order );
  for( byte[] obj : objList ){
    wrapBuffer.putByte( (byte)obj.length );
  }
}
 
private void update() {
    float cos = (float) Math.cos(rotationAngle);
    float sin = (float) Math.sin(rotationAngle);
    float matrix[] = {
        cos, sin, 0, 0,
        -sin, cos, 0, 0,
        0, 0, 1, 0,
        0, 0, 0, 1
    };
    ByteBuffer buffer = uniformBuffer.getContents();
    buffer.order(ByteOrder.nativeOrder());
    buffer.asFloatBuffer().put(matrix);

    rotationAngle += 0.01;
}
 
源代码23 项目: commons-imaging   文件: FieldTypeByteTest.java
@Test
public void testWriteDataWithNull() throws ImageWriteException {
    final FieldTypeByte fieldTypeByte = FieldType.UNDEFINED;
    final ByteOrder byteOrder = ByteOrder.BIG_ENDIAN;

    Assertions.assertThrows(ImageWriteException.class, () -> {
        fieldTypeByte.writeData( null, byteOrder);          
    });
}
 
源代码24 项目: openjdk-jdk9   文件: ImageOutputStreamImpl.java
public void writeShort(int v) throws IOException {
    if (byteOrder == ByteOrder.BIG_ENDIAN) {
        byteBuf[0] = (byte)(v >>> 8);
        byteBuf[1] = (byte)(v >>> 0);
    } else {
        byteBuf[0] = (byte)(v >>> 0);
        byteBuf[1] = (byte)(v >>> 8);
    }
    write(byteBuf, 0, 2);
}
 
private void saveMesh(NavMesh mesh, String filePostfix) throws IOException {
    // Set the flag to RecastDemo work properly
    for (int i = 0; i < mesh.getTileCount(); i++) {
        for (Poly p : mesh.getTile(i).data.polys) {
            p.flags = 1;
        }
    }

    // Save the mesh as recast file,
    MeshSetWriter writer = new MeshSetWriter();
    FileOutputStream os = new FileOutputStream(String.format("all_tiles_navmesh_%s.bin", filePostfix));
    writer.write(os, mesh, ByteOrder.LITTLE_ENDIAN, true);
    os.close();
}
 
源代码26 项目: whiskey   文件: SpdyFrameEncoder.java
public ByteBuffer encodeWindowUpdateFrame(int streamId, int deltaWindowSize) {
    byte flags = 0;
    int length = 8;
    ByteBuffer frame = ByteBuffer.allocateDirect(SPDY_HEADER_SIZE + length).order(ByteOrder.BIG_ENDIAN);
    writeControlFrameHeader(frame, SPDY_WINDOW_UPDATE_FRAME, flags, length);
    frame.putInt(streamId);
    frame.putInt(deltaWindowSize);
    frame.flip();
    return frame;
}
 
源代码27 项目: MikuMikuStudio   文件: MeshCollisionShape.java
public void read(JmeImporter im) throws IOException {
    super.read(im);
    InputCapsule capsule = im.getCapsule(this);
    numVertices = capsule.readInt("numVertices", 0);
    numTriangles = capsule.readInt("numTriangles", 0);
    vertexStride = capsule.readInt("vertexStride", 0);
    triangleIndexStride = capsule.readInt("triangleIndexStride", 0);

    triangleIndexBase = ByteBuffer.wrap(capsule.readByteArray("triangleIndexBase", new byte[0]));
    vertexBase = ByteBuffer.wrap(capsule.readByteArray("vertexBase", new byte[0])).order(ByteOrder.nativeOrder());
    createShape();
}
 
源代码28 项目: jdk8u-jdk   文件: ImageInputStreamImpl.java
public long readLong() throws IOException {
    // REMIND: Once 6277756 is fixed, we should do a bulk read of all 8
    // bytes here as we do in readShort() and readInt() for even better
    // performance (see 6347575 for details).
    int i1 = readInt();
    int i2 = readInt();

    if (byteOrder == ByteOrder.BIG_ENDIAN) {
        return ((long)i1 << 32) + (i2 & 0xFFFFFFFFL);
    } else {
        return ((long)i2 << 32) + (i1 & 0xFFFFFFFFL);
    }
}
 
源代码29 项目: netty-4.1.22   文件: CompositeByteBuf.java
@Override
protected long _getLong(int index) {
    Component c = findComponent(index);
    if (index + 8 <= c.endOffset) {
        return c.buf.getLong(index - c.offset);
    } else if (order() == ByteOrder.BIG_ENDIAN) {
        return (_getInt(index) & 0xffffffffL) << 32 | _getInt(index + 4) & 0xffffffffL;
    } else {
        return _getInt(index) & 0xFFFFFFFFL | (_getInt(index + 4) & 0xFFFFFFFFL) << 32;
    }
}
 
源代码30 项目: MOAAP   文件: CameraGLRendererBase.java
public CameraGLRendererBase(CameraGLSurfaceView view) {
    mView = view;
    int bytes = vertices.length * Float.SIZE / Byte.SIZE;
    vert   = ByteBuffer.allocateDirect(bytes).order(ByteOrder.nativeOrder()).asFloatBuffer();
    texOES = ByteBuffer.allocateDirect(bytes).order(ByteOrder.nativeOrder()).asFloatBuffer();
    tex2D  = ByteBuffer.allocateDirect(bytes).order(ByteOrder.nativeOrder()).asFloatBuffer();
    vert.put(vertices).position(0);
    texOES.put(texCoordOES).position(0);
    tex2D.put(texCoord2D).position(0);
}