Java Code Examples for java.nio.ByteOrder

The following examples show how to use java.nio.ByteOrder. These examples are extracted from open source projects.
Example 1
Project: openjdk-jdk8u   File: AudioFloatConverter.java    License: GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example 2
Project: HoloKilo   File: CubeRenderer.java    License: GNU General Public License v3.0 6 votes vote down vote up
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();
}
 
Example 3
Project: slick2d-maven   File: AiffData.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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;
}
 
Example 4
Project: grpc-nebula-java   File: AltsFraming.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 5
Project: yosegi   File: UnsafeOptimizeDumpLongColumnBinaryMaker.java    License: Apache License 2.0 6 votes vote down vote up
@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 );
    }
  }
}
 
Example 6
Project: netty-4.1.22   File: Base64Test.java    License: Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example 7
Project: conga   File: Exchange.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 8
Project: TelePlus-Android   File: SonicAudioProcessor.java    License: GNU General Public License v2.0 6 votes vote down vote up
@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;
  }
}
 
Example 9
Project: amidst   File: LocalMinecraftInterface.java    License: GNU General Public License v3.0 6 votes vote down vote up
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);
	}
}
 
Example 10
Project: MikuMikuStudio   File: BufferUtil.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
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);
    }
}
 
Example 11
Project: RxCentralBle   File: CoreParsedAdvertisement.java    License: Apache License 2.0 6 votes vote down vote up
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.
  }
}
 
Example 12
Project: flink   File: AbstractByteBufTest.java    License: Apache License 2.0 6 votes vote down vote up
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));
    }
}
 
Example 13
Project: android_9.0.0_r45   File: SurfaceTextureRenderer.java    License: Apache License 2.0 6 votes vote down vote up
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());
}
 
Example 14
Project: tracecompass   File: EventHeaderDeclarationTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * 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());
}
 
Example 15
Project: jpexs-decompiler   File: AbstractAVIStream.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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();
}
 
Example 16
Project: Building-Android-UIs-with-Custom-Views   File: GLDrawer.java    License: MIT License 6 votes vote down vote up
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);
}
 
Example 17
Project: picard   File: BclReader.java    License: MIT License 6 votes vote down vote up
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());
}
 
Example 18
Project: simplemagic   File: FloatTypeTest.java    License: ISC License 6 votes vote down vote up
@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);
}
 
Example 19
Project: hypergraphdb   File: DirectBuffer.java    License: Apache License 2.0 5 votes vote down vote up
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);
	}
}
 
Example 20
Project: MeteoInfo   File: StructureDataDeep.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 21
Project: multiple-dimension-spread   File: UnsafeOptimizeStringColumnBinaryMaker.java    License: Apache License 2.0 5 votes vote down vote up
@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 );
  }
}
 
Example 22
Project: robovm-samples   File: MetalBasic2DViewController.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 23
Project: commons-imaging   File: FieldTypeByteTest.java    License: Apache License 2.0 5 votes vote down vote up
@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);          
    });
}
 
Example 24
Project: openjdk-jdk9   File: ImageOutputStreamImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example 25
Project: recast4j   File: UnityAStarPathfindingImporterTest.java    License: zlib License 5 votes vote down vote up
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();
}
 
Example 26
Project: whiskey   File: SpdyFrameEncoder.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 27
Project: MikuMikuStudio   File: MeshCollisionShape.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
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();
}
 
Example 28
Project: jdk8u-jdk   File: ImageInputStreamImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
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);
    }
}
 
Example 29
Project: netty-4.1.22   File: CompositeByteBuf.java    License: Apache License 2.0 5 votes vote down vote up
@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;
    }
}
 
Example 30
Project: MOAAP   File: CameraGLRendererBase.java    License: MIT License 5 votes vote down vote up
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);
}
 
Example 31
Project: xDrip-plus   File: GlucoseRxMessage.java    License: GNU General Public License v3.0 5 votes vote down vote up
public GlucoseRxMessage(byte[] packet) {
    UserError.Log.d(TAG, "GlucoseRX dbg: " + JoH.bytesToHex(packet));
    if (packet.length >= 14) {
        data = ByteBuffer.wrap(packet).order(ByteOrder.LITTLE_ENDIAN);
        if ((data.get() == opcode) && checkCRC(packet)) {

            data = ByteBuffer.wrap(packet).order(ByteOrder.LITTLE_ENDIAN);

            status_raw = data.get(1);
            status = TransmitterStatus.getBatteryLevel(data.get(1));
            sequence = data.getInt(2);
            timestamp = data.getInt(6);


            int glucoseBytes = data.getShort(10); // check signed vs unsigned!!
            glucoseIsDisplayOnly = (glucoseBytes & 0xf000) > 0;
            glucose = glucoseBytes & 0xfff;

            state = data.get(12);
            trend = data.get(13);
            if (glucose > 13) {
                unfiltered = glucose * 1000;
                filtered = glucose * 1000;
            } else {
                filtered = glucose;
                unfiltered = glucose;
            }

            UserError.Log.d(TAG, "GlucoseRX: seq:" + sequence + " ts:" + timestamp + " sg:" + glucose + " do:" + glucoseIsDisplayOnly + " ss:" + status + " sr:" + status_raw + " st:" + CalibrationState.parse(state) + " tr:" + getTrend());

        }
    } else {
        UserError.Log.d(TAG, "GlucoseRxMessage packet length received wrong: " + packet.length);
    }

}
 
Example 32
Project: jreactive-8583   File: StringLengthFieldBasedFrameDecoder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected long getUnadjustedFrameLength(ByteBuf buf, int offset, int length, ByteOrder order) {
    buf = buf.order(order);
    byte[] lengthBytes = new byte[length];
    buf.getBytes(offset, lengthBytes);
    String s = new String(lengthBytes, CharsetUtil.US_ASCII);
    return Long.parseLong(s);
}
 
Example 33
Project: bytebuffer-collections   File: WrappedBitSetBitmapBitSetTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testOffHeap(){
  ByteBuffer buffer = ByteBuffer.allocateDirect(Long.SIZE * 100 / 8).order(ByteOrder.LITTLE_ENDIAN);
  BitSet testSet = BitSet.valueOf(buffer);
  testSet.set(1);
  WrappedImmutableBitSetBitmap bitMap = new WrappedImmutableBitSetBitmap(testSet);
  Assert.assertTrue(bitMap.get(1));
  testSet.set(2);
  Assert.assertTrue(bitMap.get(2));
}
 
Example 34
Project: Telegram   File: FrameworkMediaDrm.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * If the LA_URL tag is missing, injects a mock LA_URL value to avoid causing the CDM to throw
 * when creating the key request. The LA_URL attribute is optional but some Android PlayReady
 * implementations are known to require it. Does nothing it the provided {@code data} already
 * contains an LA_URL value.
 */
private static byte[] addLaUrlAttributeIfMissing(byte[] data) {
  ParsableByteArray byteArray = new ParsableByteArray(data);
  // See https://docs.microsoft.com/en-us/playready/specifications/specifications for more
  // information about the init data format.
  int length = byteArray.readLittleEndianInt();
  int objectRecordCount = byteArray.readLittleEndianShort();
  int recordType = byteArray.readLittleEndianShort();
  if (objectRecordCount != 1 || recordType != 1) {
    Log.i(TAG, "Unexpected record count or type. Skipping LA_URL workaround.");
    return data;
  }
  int recordLength = byteArray.readLittleEndianShort();
  String xml = byteArray.readString(recordLength, Charset.forName(C.UTF16LE_NAME));
  if (xml.contains("<LA_URL>")) {
    // LA_URL already present. Do nothing.
    return data;
  }
  // This PlayReady object record does not include an LA_URL. We add a mock value for it.
  int endOfDataTagIndex = xml.indexOf("</DATA>");
  if (endOfDataTagIndex == -1) {
    Log.w(TAG, "Could not find the </DATA> tag. Skipping LA_URL workaround.");
  }
  String xmlWithMockLaUrl =
      xml.substring(/* beginIndex= */ 0, /* endIndex= */ endOfDataTagIndex)
          + MOCK_LA_URL
          + xml.substring(/* beginIndex= */ endOfDataTagIndex);
  int extraBytes = MOCK_LA_URL.length() * UTF_16_BYTES_PER_CHARACTER;
  ByteBuffer newData = ByteBuffer.allocate(length + extraBytes);
  newData.order(ByteOrder.LITTLE_ENDIAN);
  newData.putInt(length + extraBytes);
  newData.putShort((short) objectRecordCount);
  newData.putShort((short) recordType);
  newData.putShort((short) (xmlWithMockLaUrl.length() * UTF_16_BYTES_PER_CHARACTER));
  newData.put(xmlWithMockLaUrl.getBytes(Charset.forName(C.UTF16LE_NAME)));
  return newData.array();
}
 
Example 35
Project: netcdf-java   File: DapDump.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void dumpbytestream(byte[] content, int start, int len, ByteOrder order, String tag) {
  System.err.println("++++++++++ " + tag + " ++++++++++ ");
  ByteBuffer tmp = ByteBuffer.wrap(content).order(order);
  tmp.position(start);
  tmp.limit(len);
  DapDump.dumpbytes(tmp);
  System.err.println("++++++++++ " + tag + " ++++++++++ ");
  System.err.flush();
}
 
Example 36
Project: Nukkit   File: Chunk.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static Chunk fromFastBinary(byte[] data, LevelProvider provider) {
    try {
        CompoundTag chunk = NBTIO.read(new DataInputStream(new ByteArrayInputStream(data)), ByteOrder.BIG_ENDIAN);
        if (!chunk.contains("Level") || !(chunk.get("Level") instanceof CompoundTag)) {
            return null;
        }

        return new Chunk(provider, chunk.getCompound("Level"));
    } catch (Exception e) {
        return null;
    }
}
 
Example 37
Project: jcuda-samples   File: JCudnnMnistUtils.java    License: MIT License 5 votes vote down vote up
private static float[] readBinaryFileAsFloats(String fileName) 
    throws IOException
{
    FileInputStream fis = new FileInputStream(new File(fileName));
    byte data[] = readFully(fis);
    ByteBuffer bb = ByteBuffer.wrap(data);
    bb.order(ByteOrder.nativeOrder());
    FloatBuffer fb = bb.asFloatBuffer();
    float result[] = new float[fb.capacity()];
    fb.get(result);
    return result;
}
 
Example 38
Project: Jupiter   File: NBTIO.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static byte[] write(CompoundTag tag, ByteOrder endianness, boolean network) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try (NBTOutputStream stream = new NBTOutputStream(baos, endianness, network)) {
        Tag.writeNamedTag(tag, stream);
        return baos.toByteArray();
    }
}
 
Example 39
Project: parquet-mr   File: PrimitiveStringifier.java    License: Apache License 2.0 5 votes vote down vote up
@Override
String stringifyNotNull(Binary value) {
  if (value.length() != 12) {
    return BINARY_INVALID;
  }
  ByteBuffer buffer = value.toByteBuffer().order(ByteOrder.LITTLE_ENDIAN);
  int pos = buffer.position();
  String months = UNSIGNED_STRINGIFIER.stringify(buffer.getInt(pos));
  String days = UNSIGNED_STRINGIFIER.stringify(buffer.getInt(pos + 4));
  String millis = UNSIGNED_STRINGIFIER.stringify(buffer.getInt(pos + 8));
  return "interval(" + months + " months, " + days + " days, " + millis + " millis)";
}
 
Example 40
Project: packer-ng-plugin   File: PayloadWriter.java    License: Apache License 2.0 5 votes vote down vote up
public static void writeBlock(File apkFile, final int id,
                              final byte[] bytes) throws IOException {
    final ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length);
    byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
    byteBuffer.put(bytes, 0, bytes.length);
    byteBuffer.flip();
    writeBlock(apkFile, id, byteBuffer);
}