Java Code Examples for java.nio.ByteOrder

The following are top voted examples for showing how to use java.nio.ByteOrder. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: openjdk-jdk10   File: Sender.java   Source Code and License 7 votes vote down vote up
public void run() {
    try {
        DatagramChannel dc = DatagramChannel.open();
        ByteBuffer bb = ByteBuffer.allocateDirect(12);
        bb.order(ByteOrder.BIG_ENDIAN);
        bb.putInt(1).putLong(1);
        bb.flip();
        InetAddress address = InetAddress.getLocalHost();
        InetSocketAddress isa = new InetSocketAddress(address, port);
        dc.connect(isa);
        clientISA = dc.getLocalAddress();
        dc.write(bb);
    } catch (Exception ex) {
        e = ex;
    }
}
 
Example 2
Project: MetadataEditor   File: Mp4BoxHeader.java   Source Code and License 6 votes vote down vote up
/**
 * Create header using headerdata, expected to find header at headerdata current position
 *
 * Note after processing adjusts position to immediately after header
 *
 * @param headerData
 */
public void update(ByteBuffer headerData)
{
    //Read header data into byte array
    byte[] b = new byte[HEADER_LENGTH];
    headerData.get(b);
    //Keep reference to copy of RawData
    dataBuffer = ByteBuffer.wrap(b);
    dataBuffer.order(ByteOrder.BIG_ENDIAN);

    //Calculate box size and id
    this.length = dataBuffer.getInt();
    this.id = Utils.readFourBytesAsChars(dataBuffer);

    logger.finest("Mp4BoxHeader id:"+id+":length:"+length);
    if (id.equals("\0\0\0\0"))
    {
        throw new NullBoxIdException(ErrorMessage.MP4_UNABLE_TO_FIND_NEXT_ATOM_BECAUSE_IDENTIFIER_IS_INVALID.getMsg(id));
    }

    if(length<HEADER_LENGTH)
    {
        throw new InvalidBoxHeaderException(ErrorMessage.MP4_UNABLE_TO_FIND_NEXT_ATOM_BECAUSE_IDENTIFIER_IS_INVALID.getMsg(id,length));
    }
}
 
Example 3
Project: openjdk-jdk10   File: VarHandleTestByteArrayAsShort.java   Source Code and License 6 votes vote down vote up
@Override
public void setupVarHandleSources() {
    // Combinations of VarHandle byte[] or ByteBuffer
    vhss = new ArrayList<>();
    for (MemoryMode endianess : Arrays.asList(MemoryMode.BIG_ENDIAN, MemoryMode.LITTLE_ENDIAN)) {

        ByteOrder bo = endianess == MemoryMode.BIG_ENDIAN
                ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN;
        VarHandleSource aeh = new VarHandleSource(
                MethodHandles.byteArrayViewVarHandle(short[].class, bo),
                endianess, MemoryMode.READ_WRITE);
        vhss.add(aeh);

        VarHandleSource bbh = new VarHandleSource(
                MethodHandles.byteBufferViewVarHandle(short[].class, bo),
                endianess, MemoryMode.READ_WRITE);
        vhss.add(bbh);
    }
}
 
Example 4
Project: PlusGram   File: NativeByteBuffer.java   Source Code and License 6 votes vote down vote up
public static NativeByteBuffer wrap(int address) {
    NativeByteBuffer result = addressWrapper.get();
    if (address != 0) {
        if (!result.reused) {
            FileLog.e("tmessages", "forgot to reuse?");
        }
        result.address = address;
        result.reused = false;
        result.buffer = native_getJavaByteBuffer(address);
        result.buffer.limit(native_limit(address));
        int position = native_position(address);
        if (position <= result.buffer.limit()) {
            result.buffer.position(position);
        }
        result.buffer.order(ByteOrder.LITTLE_ENDIAN);
    }
    return result;
}
 
Example 5
Project: burstcoin   File: AT_API_Impl.java   Source Code and License 6 votes vote down vote up
@Override
public void and_B_with_A ( AT_Machine_State state ) {
	ByteBuffer a = ByteBuffer.allocate(32);
	a.order( ByteOrder.LITTLE_ENDIAN );
	a.put(state.get_A1());
	a.put(state.get_A2());
	a.put(state.get_A3());
	a.put(state.get_A4());
	a.clear();
	
	ByteBuffer b = ByteBuffer.allocate(32);
	b.order( ByteOrder.LITTLE_ENDIAN );
	b.put(state.get_B1());
	b.put(state.get_B2());
	b.put(state.get_B3());
	b.put(state.get_B4());
	b.clear();
	
	state.set_B1(AT_API_Helper.getByteArray(a.getLong(0) & b.getLong(0)));
	state.set_B2(AT_API_Helper.getByteArray(a.getLong(8) & b.getLong(8)));
	state.set_B3(AT_API_Helper.getByteArray(a.getLong(16) & b.getLong(16)));
	state.set_B4(AT_API_Helper.getByteArray(a.getLong(24) & b.getLong(24)));
}
 
Example 6
Project: dxram   File: IBSendWorkParameterPool.java   Source Code and License 6 votes vote down vote up
/**
 * Get an instance of a (Direct)ByteBuffer for the current thread
 *
 * @return Allocated (Direct)ByteBuffer
 */
public ByteBuffer getInstance() {
    int threadId = (int) Thread.currentThread().getId();

    if (threadId > m_pool.length) {
        // Copying without lock might result in lost allocations but this can be ignored
        ByteBuffer[] tmp = new ByteBuffer[m_pool.length + INITIAL_POOL_SIZE];
        System.arraycopy(m_pool, 0, tmp, 0, m_pool.length);
        m_pool = tmp;
    }

    if (m_pool[threadId] == null) {
        m_pool[threadId] = ByteBuffer.allocateDirect(m_dataSize);
        // consider native byte order (most likely little endian)
        m_pool[threadId].order(ByteOrder.nativeOrder());
    }

    return m_pool[threadId];
}
 
Example 7
Project: sstable-adaptor   File: IndexSummary.java   Source Code and License 6 votes vote down vote up
public int binarySearch(PartitionPosition key)
{
    // We will be comparing non-native Keys, so use a buffer with appropriate byte order
    ByteBuffer hollow = MemoryUtil.getHollowDirectByteBuffer().order(ByteOrder.BIG_ENDIAN);
    int low = 0, mid = offsetCount, high = mid - 1, result = -1;
    while (low <= high)
    {
        mid = (low + high) >> 1;
        fillTemporaryKey(mid, hollow);
        result = -DecoratedKey.compareTo(partitioner, hollow, key);
        if (result > 0)
        {
            low = mid + 1;
        }
        else if (result == 0)
        {
            return mid;
        }
        else
        {
            high = mid - 1;
        }
    }

    return -mid - (result < 0 ? 1 : 2);
}
 
Example 8
Project: jdk8u-jdk   File: Type1Font.java   Source Code and License 6 votes vote down vote up
private void verifyPFB(ByteBuffer bb) throws FontFormatException {

        int pos = 0;
        while (true) {
            try {
                int segType = bb.getShort(pos) & 0xffff;
                if (segType == 0x8001 || segType == 0x8002) {
                    bb.order(ByteOrder.LITTLE_ENDIAN);
                    int segLen = bb.getInt(pos+2);
                    bb.order(ByteOrder.BIG_ENDIAN);
                    if (segLen <= 0) {
                        throw new FontFormatException("bad segment length");
                    }
                    pos += segLen+6;
                } else if (segType == 0x8003) {
                    return;
                } else {
                    throw new FontFormatException("bad pfb file");
                }
            } catch (BufferUnderflowException bue) {
                throw new FontFormatException(bue.toString());
            } catch (Exception e) {
                throw new FontFormatException(e.toString());
            }
        }
    }
 
Example 9
Project: openjdk-jdk10   File: PrevisitorTest.java   Source Code and License 6 votes vote down vote up
public void test() throws Exception {
    CustomPlugin plugin = new CustomPlugin();
    PluginRepository.registerPlugin(plugin);
    List<Plugin> plugins = new ArrayList<>();
    plugins.add(createPlugin(CustomPlugin.NAME));
    ImagePluginStack stack = ImagePluginConfiguration.parseConfiguration(new Jlink.PluginsConfiguration(plugins,
            null, null));
    ResourcePoolManager inResources = new ResourcePoolManager(ByteOrder.nativeOrder(), new CustomStringTable());
    inResources.add(ResourcePoolEntry.create("/aaa/bbb/res1.class", new byte[90]));
    inResources.add(ResourcePoolEntry.create("/aaa/bbb/res2.class", new byte[90]));
    inResources.add(ResourcePoolEntry.create("/aaa/bbb/res3.class", new byte[90]));
    inResources.add(ResourcePoolEntry.create("/aaa/ddd/res1.class", new byte[90]));
    inResources.add(ResourcePoolEntry.create("/aaa/res1.class", new byte[90]));
    ResourcePool outResources = stack.visitResources(inResources);
    Collection<String> input = inResources.entries()
            .map(Object::toString)
            .collect(Collectors.toList());
    Collection<String> output = outResources.entries()
            .map(Object::toString)
            .collect(Collectors.toList());
    if (!input.equals(output)) {
        throw new AssertionError("Input and output resources differ: input: "
                + input + ", output: " + output);
    }
}
 
Example 10
Project: Jenisys3   File: ChunkRequestTask.java   Source Code and License 6 votes vote down vote up
public ChunkRequestTask(Level level, Chunk chunk) {
    this.levelId = level.getId();
    this.chunk = chunk.toFastBinary();
    this.chunkX = chunk.getX();
    this.chunkZ = chunk.getZ();

    byte[] buffer = new byte[0];

    for (BlockEntity blockEntity : chunk.getBlockEntities().values()) {
        if (blockEntity instanceof BlockEntitySpawnable) {
            try {
                buffer = Binary.appendBytes(buffer, NBTIO.write(((BlockEntitySpawnable) blockEntity).getSpawnCompound(), ByteOrder.BIG_ENDIAN, true));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }
    }

    this.blockEntities = buffer;
}
 
Example 11
Project: memory   File: BufferTest2.java   Source Code and License 6 votes vote down vote up
@Test
public void testAsMemory() {
  ByteBuffer bb = ByteBuffer.allocate(64).order(ByteOrder.nativeOrder());

  Byte b = 0;
  while (bb.hasRemaining()) {
    bb.put(b);
    b++;
  }
  bb.position(10);

  Buffer buffer = Buffer.wrap(bb);
  Memory memory = buffer.asMemory();

  assertEquals(buffer.getCapacity(), memory.getCapacity());

  while(buffer.hasRemaining()){
    assertEquals(memory.getByte(buffer.getPosition()), buffer.getByte());
  }
}
 
Example 12
Project: GitHub   File: GifHeaderParserTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testCanReadValidHeaderAndLSD() {
  final int width = 10;
  final int height = 20;
  ByteBuffer buffer =
      ByteBuffer.allocate(GifBytesTestUtil.HEADER_LENGTH).order(ByteOrder.LITTLE_ENDIAN);
  GifBytesTestUtil.writeHeaderAndLsd(buffer, width, height, false, 0);

  parser.setData(buffer.array());
  GifHeader header = parser.parseHeader();
  assertEquals(width, header.width);
  assertEquals(height, header.height);
  assertFalse(header.gctFlag);
  // 2^(1+0) == 2^1 == 2.
  assertEquals(2, header.gctSize);
  assertEquals(0, header.bgIndex);
  assertEquals(0, header.pixelAspect);
}
 
Example 13
Project: BaseClient   File: WaveData.java   Source Code and License 6 votes vote down vote up
/**
 * Convert the audio bytes into the stream
 * 
 * @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(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.LITTLE_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())
			dest.put(src.get());
	}
	dest.rewind();
	return dest;
}
 
Example 14
Project: GitHub   File: GifHeaderParserTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testCanParseMultipleFrames() {
  final int lzwMinCodeSize = 2;
  final int expectedFrames = 3;

  final int frameSize = GifBytesTestUtil.IMAGE_DESCRIPTOR_LENGTH + GifBytesTestUtil
      .getImageDataSize(lzwMinCodeSize);
  ByteBuffer buffer =
      ByteBuffer.allocate(GifBytesTestUtil.HEADER_LENGTH + expectedFrames * frameSize)
          .order(ByteOrder.LITTLE_ENDIAN);

  GifBytesTestUtil.writeHeaderAndLsd(buffer, 1, 1, false, 0);
  for (int i = 0; i < expectedFrames; i++) {
    GifBytesTestUtil.writeImageDescriptor(buffer, 0, 0, 1, 1, false /*hasLct*/, 0 /*numColors*/);
    GifBytesTestUtil.writeFakeImageData(buffer, 2);
  }

  parser.setData(buffer.array());
  GifHeader header = parser.parseHeader();
  assertEquals(expectedFrames, header.frameCount);
  assertEquals(expectedFrames, header.frames.size());
}
 
Example 15
Project: GitHub   File: GifHeaderParserTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testIsNotAnimatedOneFrame() {
  final int lzwMinCodeSize = 2;

  final int frameSize =
      GifBytesTestUtil.IMAGE_DESCRIPTOR_LENGTH
          + GifBytesTestUtil.getImageDataSize(lzwMinCodeSize);

  ByteBuffer buffer =
      ByteBuffer.allocate(GifBytesTestUtil.HEADER_LENGTH + frameSize)
          .order(ByteOrder.LITTLE_ENDIAN);

  GifBytesTestUtil.writeHeaderAndLsd(buffer, 1, 1, false, 0);
  GifBytesTestUtil.writeImageDescriptor(buffer, 0, 0, 1, 1, false /*hasLct*/, 0 /*numColors*/);
  GifBytesTestUtil.writeFakeImageData(buffer, 2);

  parser.setData(buffer.array());
  assertFalse(parser.isAnimated());
}
 
Example 16
Project: jdk8u-jdk   File: AudioFloatConverter.java   Source Code and License 6 votes vote down vote up
public byte[] toByteArray(float[] in_buff, int in_offset, int in_len,
        byte[] out_buff, int out_offset) {
    int out_len = in_len * 8;
    if (bytebuffer == null || bytebuffer.capacity() < out_len) {
        bytebuffer = ByteBuffer.allocate(out_len).order(
                ByteOrder.LITTLE_ENDIAN);
        floatbuffer = bytebuffer.asDoubleBuffer();
    }
    floatbuffer.position(0);
    bytebuffer.position(0);
    if (double_buff == null || double_buff.length < in_offset + in_len)
        double_buff = new double[in_offset + in_len];
    int in_offset_end = in_offset + in_len;
    for (int i = in_offset; i < in_offset_end; i++) {
        double_buff[i] = in_buff[i];
    }
    floatbuffer.put(double_buff, in_offset, in_len);
    bytebuffer.get(out_buff, out_offset, out_len);
    return out_buff;
}
 
Example 17
Project: atlas   File: Dex.java   Source Code and License 6 votes vote down vote up
/**
 * Creates a new dex from the contents of {@code bytes}. This API supports
 * both {@code .dex} and {@code .odex} input. Calling this constructor
 * transfers ownership of {@code bytes} to the returned Dex: it is an error
 * to access the buffer after calling this method.
 */
public static Dex create(ByteBuffer data) throws IOException {
    data.order(ByteOrder.LITTLE_ENDIAN);

    // if it's an .odex file, set position and limit to the .dex section
    if (data.get(0) == 'd' && data.get(1) == 'e' && data.get(2) == 'y' && data.get(3) == '\n') {
        data.position(8);
        int offset = data.getInt();
        int length = data.getInt();
        data.position(offset);
        data.limit(offset + length);
        data = data.slice();
    }

    return new Dex(data);
}
 
Example 18
Project: boohee_v5.6   File: Memory.java   Source Code and License 6 votes vote down vote up
public static void pokeInt(byte[] dst, int offset, int value, ByteOrder order) {
    if (order == ByteOrder.BIG_ENDIAN) {
        int i = offset + 1;
        dst[offset] = (byte) ((value >> 24) & 255);
        offset = i + 1;
        dst[i] = (byte) ((value >> 16) & 255);
        i = offset + 1;
        dst[offset] = (byte) ((value >> 8) & 255);
        dst[i] = (byte) ((value >> 0) & 255);
        offset = i;
        return;
    }
    i = offset + 1;
    dst[offset] = (byte) ((value >> 0) & 255);
    offset = i + 1;
    dst[i] = (byte) ((value >> 8) & 255);
    i = offset + 1;
    dst[offset] = (byte) ((value >> 16) & 255);
    dst[i] = (byte) ((value >> 24) & 255);
    offset = i;
}
 
Example 19
Project: traccar-service   File: CellocatorProtocolDecoder.java   Source Code and License 6 votes vote down vote up
private void sendReply(Channel channel, SocketAddress remoteAddress, long deviceId, byte packetNumber) {
    ChannelBuffer reply = ChannelBuffers.directBuffer(ByteOrder.LITTLE_ENDIAN, 28);
    reply.writeByte('M');
    reply.writeByte('C');
    reply.writeByte('G');
    reply.writeByte('P');
    reply.writeByte(MSG_SERVER_ACKNOWLEDGE);
    reply.writeInt((int) deviceId);
    reply.writeByte(commandCount++);
    reply.writeInt(0); // authentication code
    reply.writeByte(0);
    reply.writeByte(packetNumber);
    reply.writeZero(11);

    byte checksum = 0;
    for (int i = 4; i < 27; i++) {
        checksum += reply.getByte(i);
    }
    reply.writeByte(checksum);

    if (channel != null) {
        channel.write(reply, remoteAddress);
    }
}
 
Example 20
Project: Jupiter   File: Chunk.java   Source Code and License 5 votes vote down vote up
public static Chunk fromBinary(byte[] data, LevelProvider provider) {
    try {
        CompoundTag chunk = NBTIO.read(new ByteArrayInputStream(Zlib.inflate(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) {
        Server.getInstance().getLogger().logException(e);
        return null;
    }
}
 
Example 21
Project: MegviiFacepp-Android-SDK   File: PointsMatrix.java   Source Code and License 5 votes vote down vote up
public FloatBuffer floatBufferUtil(float[] arr) {
	// 初始化ByteBuffer,长度为arr数组的长度*4,因为一个int占4个字节
	ByteBuffer qbb = ByteBuffer.allocateDirect(arr.length * 4);
	// 数组排列用nativeOrder
	qbb.order(ByteOrder.nativeOrder());
	FloatBuffer mBuffer = qbb.asFloatBuffer();
	mBuffer.put(arr);
	mBuffer.position(0);
	return mBuffer;
}
 
Example 22
Project: MOAAP   File: CameraGLRendererBase.java   Source Code and 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 23
Project: Android_OpenGL_Demo   File: LessonFiveRenderer.java   Source Code and License 5 votes vote down vote up
/**
 * Initialize the model data.
 */
public LessonFiveRenderer(final Context activityContext)
{	
	mActivityContext = activityContext;
	
	// Define points for a cube.
	// X, Y, Z
	final float[] p1p = {-1.0f, 1.0f, 1.0f};					
	final float[] p2p = {1.0f, 1.0f, 1.0f};
	final float[] p3p = {-1.0f, -1.0f, 1.0f};
	final float[] p4p = {1.0f, -1.0f, 1.0f};
	final float[] p5p = {-1.0f, 1.0f, -1.0f};
	final float[] p6p = {1.0f, 1.0f, -1.0f};
	final float[] p7p = {-1.0f, -1.0f, -1.0f};
	final float[] p8p = {1.0f, -1.0f, -1.0f};		
	
	final float[] cubePositionData = ShapeBuilder.generateCubeData(p1p, p2p, p3p, p4p, p5p, p6p, p7p, p8p, p1p.length);
	
	// Points of the cube: color information
	// R, G, B, A
	final float[] p1c = {1.0f, 0.0f, 0.0f, 1.0f};		// red			
	final float[] p2c = {1.0f, 0.0f, 1.0f, 1.0f};		// magenta
	final float[] p3c = {0.0f, 0.0f, 0.0f, 1.0f};		// black
	final float[] p4c = {0.0f, 0.0f, 1.0f, 1.0f};		// blue
	final float[] p5c = {1.0f, 1.0f, 0.0f, 1.0f};		// yellow
	final float[] p6c = {1.0f, 1.0f, 1.0f, 1.0f};		// white
	final float[] p7c = {0.0f, 1.0f, 0.0f, 1.0f};		// green
	final float[] p8c = {0.0f, 1.0f, 1.0f, 1.0f};		// cyan
	
	final float[] cubeColorData = ShapeBuilder.generateCubeData(p1c, p2c, p3c, p4c, p5c, p6c, p7c, p8c, p1c.length);				
	
	// Initialize the buffers.
	mCubePositions = ByteBuffer.allocateDirect(cubePositionData.length * mBytesPerFloat)
       .order(ByteOrder.nativeOrder()).asFloatBuffer();							
	mCubePositions.put(cubePositionData).position(0);		
	
	mCubeColors = ByteBuffer.allocateDirect(cubeColorData.length * mBytesPerFloat)
       .order(ByteOrder.nativeOrder()).asFloatBuffer();							
	mCubeColors.put(cubeColorData).position(0);
}
 
Example 24
Project: traccar-service   File: Pt502Protocol.java   Source Code and License 5 votes vote down vote up
@Override
public void initTrackerServers(List<TrackerServer> serverList) {
    TrackerServer server = new TrackerServer(new ServerBootstrap(), getName()) {
        @Override
        protected void addSpecificHandlers(ChannelPipeline pipeline) {
            pipeline.addLast("frameDecoder", new Pt502FrameDecoder());
            pipeline.addLast("stringEncoder", new StringEncoder());
            pipeline.addLast("stringDecoder", new StringDecoder());
            pipeline.addLast("objectEncoder", new Pt502ProtocolEncoder());
            pipeline.addLast("objectDecoder", new Pt502ProtocolDecoder(Pt502Protocol.this));
        }
    };
    server.setEndianness(ByteOrder.LITTLE_ENDIAN);
    serverList.add(server);
}
 
Example 25
Project: atlas   File: Dex.java   Source Code and License 5 votes vote down vote up
public Section appendSection(int maxByteCount, String name) {
    if ((maxByteCount & 3) != 0) {
        throw new IllegalStateException("Not four byte aligned!");
    }
    int limit = nextSectionStart + maxByteCount;
    ByteBuffer sectionData = data.duplicate();
    sectionData.order(ByteOrder.LITTLE_ENDIAN); // necessary?
    sectionData.position(nextSectionStart);
    sectionData.limit(limit);
    Section result = new Section(name, sectionData);
    nextSectionStart = limit;
    return result;
}
 
Example 26
Project: traccar-service   File: BceProtocol.java   Source Code and License 5 votes vote down vote up
@Override
public void initTrackerServers(List<TrackerServer> serverList) {
    TrackerServer server = new TrackerServer(new ServerBootstrap(), getName()) {
        @Override
        protected void addSpecificHandlers(ChannelPipeline pipeline) {
            pipeline.addLast("frameDecoder", new BceFrameDecoder());
            pipeline.addLast("objectDecoder", new BceProtocolDecoder(BceProtocol.this));
        }
    };
    server.setEndianness(ByteOrder.LITTLE_ENDIAN);
    serverList.add(server);
}
 
Example 27
Project: BaseClient   File: WorldRenderer.java   Source Code and License 5 votes vote down vote up
private void putColorRGBA(int index, int red, int p_178972_3_, int p_178972_4_, int p_178972_5_)
{
    if (ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN)
    {
        this.rawIntBuffer.put(index, p_178972_5_ << 24 | p_178972_4_ << 16 | p_178972_3_ << 8 | red);
    }
    else
    {
        this.rawIntBuffer.put(index, red << 24 | p_178972_3_ << 16 | p_178972_4_ << 8 | p_178972_5_);
    }
}
 
Example 28
Project: CustomWorldGen   File: VertexBuffer.java   Source Code and License 5 votes vote down vote up
/**
 * Modify the color data of the given vertex with the given multipliers.
 *  
 * @param vertexIndex The index of the vertex to modify, where 0 is the last one added, 1 is the second last, etc.
 */
public void putColorMultiplier(float red, float green, float blue, int vertexIndex)
{
    int i = this.getColorIndex(vertexIndex);
    int j = -1;

    if (!this.noColor)
    {
        j = this.rawIntBuffer.get(i);

        if (ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN)
        {
            int k = (int)((float)(j & 255) * red);
            int l = (int)((float)(j >> 8 & 255) * green);
            int i1 = (int)((float)(j >> 16 & 255) * blue);
            j = j & -16777216;
            j = j | i1 << 16 | l << 8 | k;
        }
        else
        {
            int j1 = (int)((float)(j >> 24 & 255) * red);
            int k1 = (int)((float)(j >> 16 & 255) * green);
            int l1 = (int)((float)(j >> 8 & 255) * blue);
            j = j & 255;
            j = j | j1 << 24 | k1 << 16 | l1 << 8;
        }
    }

    this.rawIntBuffer.put(i, j);
}
 
Example 29
Project: MetadataEditor   File: WavTagWriter.java   Source Code and License 5 votes vote down vote up
/**
 * Seek in file to start of LIST Metadata chunk
 *
 * @param fc
 * @param existingTag
 * @throws IOException
 * @throws CannotWriteException
 */
private ChunkHeader seekToStartOfListInfoMetadata(FileChannel fc, WavTag existingTag) throws IOException, CannotWriteException {
    fc.position(existingTag.getInfoTag().getStartLocationInFile());
    final ChunkHeader chunkHeader = new ChunkHeader(ByteOrder.LITTLE_ENDIAN);
    chunkHeader.readHeader(fc);
    fc.position(fc.position() - ChunkHeader.CHUNK_HEADER_SIZE);

    if (!WavChunkType.LIST.getCode().equals(chunkHeader.getID())) {
        throw new CannotWriteException(loggingName + " Unable to find List chunk at original location has file been modified externally");
    }
    return chunkHeader;
}
 
Example 30
Project: Nukkit-Java9   File: NBTInputStream.java   Source Code and License 5 votes vote down vote up
@Override
public int readUnsignedShort() throws IOException {
    int s = this.stream.readUnsignedShort();
    if (endianness == ByteOrder.LITTLE_ENDIAN) {
        s = Integer.reverseBytes(s) >> 16;
    }
    return s;
}
 
Example 31
Project: openjdk-jdk10   File: ResourcePoolManager.java   Source Code and License 5 votes vote down vote up
public ResourcePoolManager(ByteOrder order) {
    this(order, new StringTable() {

        @Override
        public int addString(String str) {
            return -1;
        }

        @Override
        public String getString(int id) {
            return null;
        }
    });
}
 
Example 32
Project: guava-mock   File: StatsTest.java   Source Code and License 5 votes vote down vote up
public void testFromByteArray_withTooLongArrayInputThrowsIllegalArgumentException() {
  byte[] buffer = MANY_VALUES_STATS_VARARGS.toByteArray();
  byte[] tooLongByteArray = ByteBuffer.allocate(buffer.length + 2).order(ByteOrder.LITTLE_ENDIAN)
      .put(buffer).putChar('.').array();
  try {
    Stats.fromByteArray(tooLongByteArray);
    fail("Expected IllegalArgumentException");
  } catch (IllegalArgumentException expected) {
  }
}
 
Example 33
Project: aos-Video   File: OpenSubtitlesHasher.java   Source Code and License 5 votes vote down vote up
private static long computeHashForChunk(ByteBuffer buffer) {
        
        LongBuffer longBuffer = buffer.order(ByteOrder.LITTLE_ENDIAN).asLongBuffer();
        long hash = 0;
        while (longBuffer.hasRemaining()) {
                hash += longBuffer.get();
        }
        
        return hash;
}
 
Example 34
Project: azeroth   File: HashUtils.java   Source Code and License 5 votes vote down vote up
/**
 * MurMurHash算法,是非加密HASH算法,性能很高,
 * 比传统的CRC32,MD5,SHA-1(这两个算法都是加密HASH算法,复杂度本身就很高,带来的性能上的损害也不可避免)
 * 等HASH算法要快很多,而且据说这个算法的碰撞率很低. http://murmurhash.googlepages.com/
 */
public static Long hash(String key) {
    if (key == null) { return 0L; }
    ByteBuffer buf = ByteBuffer.wrap(key.getBytes());
    int seed = 0x1234ABCD;

    ByteOrder byteOrder = buf.order();
    buf.order(ByteOrder.LITTLE_ENDIAN);

    long m = 0xc6a4a7935bd1e995L;
    int r = 47;

    long h = seed ^ (buf.remaining() * m);

    long k;
    while (buf.remaining() >= 8) {
        k = buf.getLong();

        k *= m;
        k ^= k >>> r;
        k *= m;

        h ^= k;
        h *= m;
    }

    if (buf.remaining() > 0) {
        ByteBuffer finish = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN);
        finish.put(buf).rewind();
        h ^= finish.getLong();
        h *= m;
    }

    h ^= h >>> r;
    h *= m;
    h ^= h >>> r;

    buf.order(byteOrder);
    return Math.abs(h);
}
 
Example 35
Project: tuxguitar   File: AudioFloatConverter.java   Source Code and License 5 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 * 4;
    if (bytebuffer == null || bytebuffer.capacity() < in_len) {
        bytebuffer = ByteBuffer.allocate(in_len).order(
                ByteOrder.BIG_ENDIAN);
        floatbuffer = bytebuffer.asFloatBuffer();
    }
    bytebuffer.position(0);
    floatbuffer.position(0);
    bytebuffer.put(in_buff, in_offset, in_len);
    floatbuffer.get(out_buff, out_offset, out_len);
    return out_buff;
}
 
Example 36
Project: MetadataEditor   File: OggVorbisTagWriter.java   Source Code and License 5 votes vote down vote up
/**
 * Create a second Page, and add comment header to it, but page is incomplete may want to add addition header and need to calculate CRC
 *
 * @param vorbisHeaderSizes
 * @param newCommentLength
 * @param newSecondPageLength
 * @param secondPageHeader
 * @param newComment
 * @return
 * @throws IOException
 */
private ByteBuffer startCreateBasicSecondPage(
        OggVorbisTagReader.OggVorbisHeaderSizes vorbisHeaderSizes,
        int newCommentLength,
        int newSecondPageLength,
        OggPageHeader secondPageHeader,
        ByteBuffer newComment) throws IOException
{
    logger.fine("WriteOgg Type 1");
    byte[] segmentTable = createSegmentTable(newCommentLength, vorbisHeaderSizes.getSetupHeaderSize(), vorbisHeaderSizes.getExtraPacketList());
    int newSecondPageHeaderLength = OggPageHeader.OGG_PAGE_HEADER_FIXED_LENGTH + segmentTable.length;
    logger.fine("New second page header length:" + newSecondPageHeaderLength);
    logger.fine("No of segments:" + segmentTable.length);

    ByteBuffer secondPageBuffer = ByteBuffer.allocate(newSecondPageLength + newSecondPageHeaderLength);
    secondPageBuffer.order(ByteOrder.LITTLE_ENDIAN);

    //Build the new 2nd page header, can mostly be taken from the original upto the segment length OggS capture
    secondPageBuffer.put(secondPageHeader.getRawHeaderData(), 0, OggPageHeader.OGG_PAGE_HEADER_FIXED_LENGTH - 1);

    //Number of Page Segments
    secondPageBuffer.put((byte) segmentTable.length);

    //Page segment table
    for (byte aSegmentTable : segmentTable)
    {
        secondPageBuffer.put(aSegmentTable);
    }

    //Add New VorbisComment
    secondPageBuffer.put(newComment);
    return secondPageBuffer;

}
 
Example 37
Project: Jenisys3   File: NBTInputStream.java   Source Code and License 5 votes vote down vote up
@Override
public short readShort() throws IOException {
    short s = this.stream.readShort();
    if (endianness == ByteOrder.LITTLE_ENDIAN) {
        s = Short.reverseBytes(s);
    }
    return s;
}
 
Example 38
Project: incubator-netbeans   File: BinaryFS.java   Source Code and License 5 votes vote down vote up
/**
 * A method for fetching/parsing the content of the file/folder
 * to the memory. Should be called before any access operation
 * to check the content of the entity.
 */
protected final void initialize() {
    if (initialized) return;

    try {
        ByteBuffer sub = (ByteBuffer)content.duplicate().order(ByteOrder.LITTLE_ENDIAN).position(offset);
        if (!isRoot()) {
            while (sub.getInt() >= 0) {
                // skip URL list
            }
        }

        int attrCount = sub.getInt();
        if (attrCount > 0) attrs = new HashMap<String, AttrImpl>(attrCount*4/3+1);

        for (int i=0; i< attrCount; i++) {  // do read attribute
            // attribute names are highly duplicated!
            String attrName = getString(sub);   // String attrName
            byte type = sub.get();          // byte attrType
            // values have high redundancy as well,
            // like "true", "JSeparator", paths to orig files from
            // shadow, ...
            String value = getString(sub);  // String attrValue
            attrs.put(attrName, new AttrImpl(type, value));
        }

        doInitialize(sub);
    } catch (Exception e) {
        System.err.println("exception in initialize() on " + name + ": " + e);
    }
    initialized = true;
}
 
Example 39
Project: traccar-service   File: BlackKiteProtocol.java   Source Code and License 5 votes vote down vote up
@Override
public void initTrackerServers(List<TrackerServer> serverList) {
    TrackerServer server = new TrackerServer(new ServerBootstrap(), getName()) {
        @Override
        protected void addSpecificHandlers(ChannelPipeline pipeline) {
            pipeline.addLast("frameDecoder", new GalileoFrameDecoder());
            pipeline.addLast("objectDecoder", new BlackKiteProtocolDecoder(BlackKiteProtocol.this));
        }
    };
    server.setEndianness(ByteOrder.LITTLE_ENDIAN);
    serverList.add(server);
}
 
Example 40
Project: FilterPlayer   File: GPUImageFilter.java   Source Code and License 5 votes vote down vote up
public GPUImageFilter(final String vertexShader, final String fragmentShader) {
    mRunOnDraw = new LinkedList<>();
    mVertexShader = vertexShader;
    mFragmentShader = fragmentShader;

    mGLCubeBuffer = ByteBuffer.allocateDirect(TextureRotationUtil.CUBE.length * 4)
            .order(ByteOrder.nativeOrder())
            .asFloatBuffer();
    mGLCubeBuffer.put(TextureRotationUtil.CUBE).position(0);

    mGLTextureBuffer = ByteBuffer.allocateDirect(TextureRotationUtil.TEXTURE_NO_ROTATION.length * 4)
            .order(ByteOrder.nativeOrder())
            .asFloatBuffer();
    mGLTextureBuffer.put(TextureRotationUtil.getRotation(Rotation.NORMAL, false, true)).position(0);
}