Java Code Examples for java.nio.ByteBuffer.order()

The following are Jave code examples for showing how to use order() of the java.nio.ByteBuffer class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: burstcoin   File: AT_API_Impl.java   View Source Code Vote up 6 votes
@Override
public long check_HASH160_A_with_B( AT_Machine_State state ) {
	if ( state.getHeight() >= Constants.AT_FIX_BLOCK_3 ) {
		ByteBuffer b = ByteBuffer.allocate( 32 );
		b.order( ByteOrder.LITTLE_ENDIAN );
		
		b.put( state.get_A1() );
		b.put( state.get_A2() );
		b.put( state.get_A3() );
		b.put( state.get_A4() );
		
		RIPEMD160 ripemd160 = new RIPEMD160();
		ByteBuffer ripemdb = ByteBuffer.wrap( ripemd160.digest( b.array() ) );
		ripemdb.order( ByteOrder.LITTLE_ENDIAN );
		
		return ( ripemdb.getLong(0) == AT_API_Helper.getLong( state.get_B1() ) &&
				 ripemdb.getLong(8) == AT_API_Helper.getLong( state.get_B2() ) &&
				 ripemdb.getInt(16) == ((int)(AT_API_Helper.getLong( state.get_B3() ) & 0x00000000FFFFFFFFL ))
				 ) ? 1 : 0;
	}
	else {
		return(Arrays.equals(state.get_A1(), state.get_B1()) &&
				Arrays.equals(state.get_A2(), state.get_B2()) &&
				(AT_API_Helper.getLong(state.get_A3()) & 0x00000000FFFFFFFFL) == (AT_API_Helper.getLong(state.get_B3()) & 0x00000000FFFFFFFFL)) ? 1 : 0;
	}
}
 
Example 2
Project: burstcoin   File: AT_API_Helper.java   View Source Code Vote up 5 votes
protected static long getLongTimestamp(int height, int numOfTx){
	ByteBuffer buffer = ByteBuffer.allocate(8);
	buffer.order(ByteOrder.LITTLE_ENDIAN);
	buffer.putInt(4, height);
	buffer.putInt(0,numOfTx);
	return buffer.getLong(0);
}
 
Example 3
Project: crypto-core   File: NativeSecp256k1.java   View Source Code Vote up 5 votes
public static byte[] schnorrSign(byte[] data, byte[] sec) throws AssertFailException {
    Preconditions.checkArgument(data.length == 32 && sec.length <= 32);

    ByteBuffer byteBuff = nativeECDSABuffer.get();
    if (byteBuff == null) {
        byteBuff = ByteBuffer.allocateDirect(32 + 32);
        byteBuff.order(ByteOrder.nativeOrder());
        nativeECDSABuffer.set(byteBuff);
    }
    byteBuff.rewind();
    byteBuff.put(data);
    byteBuff.put(sec);

    byte[][] retByteArray;

    r.lock();
    try {
        retByteArray = secp256k1_schnorr_sign(byteBuff, Secp256k1Context.getContext());
    } finally {
        r.unlock();
    }

    byte[] sigArr = retByteArray[0];
    int retVal = new BigInteger(new byte[] { retByteArray[1][0] }).intValue();

    assertEquals(sigArr.length, 64, "Got bad signature length.");

    return retVal == 0 ? new byte[0] : sigArr;
}
 
Example 4
Project: memory   File: MemoryTest.java   View Source Code Vote up 5 votes
@Test
public void checkByteBufWrongOrder() {
  int n = 1024; //longs
  ByteBuffer bb = ByteBuffer.allocate(n * 8);
  bb.order(ByteOrder.BIG_ENDIAN);
  Memory mem = Memory.wrap(bb);
  assertTrue(mem.swapBytes());
  assertEquals(mem.getResourceOrder(), ByteOrder.BIG_ENDIAN);
}
 
Example 5
Project: Word2VecfJava   File: WordVectorSerializer.java   View Source Code Vote up 5 votes
/** Save the word2vecf model as binary file */
public static void saveWord2VecfToBinary (String wordToPath, String contextToPath, Word2Vecf w2vf) {
	final Charset cs = StandardCharsets.UTF_8;
	try {
		final OutputStream wos = new FileOutputStream(new File(wordToPath));
		final String wheader = String.format("%d %d\n", w2vf.wordVocabSize(), w2vf.getLayerSize());
		wos.write(wheader.getBytes(cs));
		final ByteBuffer wbuffer = ByteBuffer.allocate(4 * w2vf.getLayerSize());
		wbuffer.order(byteOrder);
		for (int i = 0; i < w2vf.wordVocabSize(); ++i) {
			wos.write(String.format("%s ", w2vf.getWordVocab().get(i)).getBytes(cs));
			wbuffer.clear();
			for (int j = 0; j < w2vf.getLayerSize(); ++j) wbuffer.putFloat(w2vf.getWordVectors().getFloat(i, j));
			wos.write(wbuffer.array());
			wos.write('\n');
		}
		wos.flush();
		wos.close();
		final OutputStream cos = new FileOutputStream(new File(contextToPath));
		final String cheader = String.format("%d %d\n", w2vf.contextVocabSize(), w2vf.getLayerSize());
		cos.write(cheader.getBytes(cs));
		final ByteBuffer cbuffer = ByteBuffer.allocate(4 * w2vf.getLayerSize());
		cbuffer.order(byteOrder);
		for (int i = 0; i < w2vf.contextVocabSize(); ++i) {
			cos.write(String.format("%s ", w2vf.getContextVocab().get(i)).getBytes(cs));
			cbuffer.clear();
			for (int j = 0; j < w2vf.getLayerSize(); ++j) cbuffer.putFloat(w2vf.getContextVectors().getFloat(i, j));
			cos.write(cbuffer.array());
			cos.write('\n');
		}
		cos.flush();
		cos.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 6
Project: okwallet   File: NativeSecp256k1.java   View Source Code Vote up 5 votes
/**
 * libsecp256k1 Compute Pubkey - computes public key from secret key
 *
 * @param seckey ECDSA Secret key, 32 bytes
 * @return pubkey ECDSA Public key, 33 or 65 bytes
 */
// TODO add a 'compressed' arg
public static byte[] computePubkey(byte[] seckey) throws AssertFailException {
    Preconditions.checkArgument(seckey.length == 32);

    ByteBuffer byteBuff = nativeECDSABuffer.get();
    if (byteBuff == null || byteBuff.capacity() < seckey.length) {
        byteBuff = ByteBuffer.allocateDirect(seckey.length);
        byteBuff.order(ByteOrder.nativeOrder());
        nativeECDSABuffer.set(byteBuff);
    }
    byteBuff.rewind();
    byteBuff.put(seckey);

    byte[][] retByteArray;

    r.lock();
    try {
        retByteArray = secp256k1_ec_pubkey_create(byteBuff, Secp256k1Context.getContext());
    } finally {
        r.unlock();
    }

    byte[] pubArr = retByteArray[0];
    int pubLen = new BigInteger(new byte[] { retByteArray[1][0] }).intValue();
    int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue();

    assertEquals(pubArr.length, pubLen, "Got bad pubkey length.");

    return retVal == 0 ? new byte[0] : pubArr;
}
 
Example 7
Project: burstcoin   File: AT_API_Helper.java   View Source Code Vote up 5 votes
public static byte[] getByteArray( long l ){
	ByteBuffer buffer = ByteBuffer.allocate(8);
	buffer.order(ByteOrder.LITTLE_ENDIAN);
	buffer.clear();
	buffer.putLong( l );
	return buffer.array();
}
 
Example 8
Project: AnimationsDemo   File: MCPTool.java   View Source Code Vote up 5 votes
/**
 * 字节数组转换成short(小端序)
 * @param stream
 * @param offset
 * @return
 */
private static byte[] short2Stream(short data) {
       ByteBuffer buffer = ByteBuffer.allocate(2);
       buffer.order(ByteOrder.LITTLE_ENDIAN);
       buffer.putShort(data);
       buffer.flip();
       return buffer.array();
   }
 
Example 9
Project: s-store   File: ByteBufferFifo.java   View Source Code Vote up 5 votes
private ByteBuffer allocateBuffer() {
    ByteBuffer buffer = emptyBuffers.pollLast();
    if (buffer == null) {
        buffer = ByteBuffer.allocateDirect(BUFFER_SIZE);
        if (!bigEndian) {
            buffer.order(ByteOrder.nativeOrder());
        }
    }
    return buffer;
}
 
Example 10
Project: coffee-gb   File: FileBattery.java   View Source Code Vote up 5 votes
private void loadClock(long[] clockData, InputStream is) throws IOException {
    byte[] byteBuff = new byte[4 * clockData.length];
    IOUtils.read(is, byteBuff);
    ByteBuffer buff = ByteBuffer.wrap(byteBuff);
    buff.order(ByteOrder.LITTLE_ENDIAN);
    int i = 0;
    while (buff.hasRemaining()) {
        clockData[i++] = buff.getInt() & 0xffffffff;
    }
}
 
Example 11
Project: crypto-core   File: NativeSecp256k1.java   View Source Code Vote up 5 votes
/**
 * libsecp256k1 PubKey Tweak-Mul - Tweak pubkey by multiplying to it
 *
 * @param tweak some bytes to tweak with
 * @param pubkey 32-byte seckey
 */
public static byte[] pubKeyTweakMul(byte[] pubkey, byte[] tweak) throws AssertFailException {
    Preconditions.checkArgument(pubkey.length == 33 || pubkey.length == 65);

    ByteBuffer byteBuff = nativeECDSABuffer.get();
    if (byteBuff == null || byteBuff.capacity() < pubkey.length + tweak.length) {
        byteBuff = ByteBuffer.allocateDirect(pubkey.length + tweak.length);
        byteBuff.order(ByteOrder.nativeOrder());
        nativeECDSABuffer.set(byteBuff);
    }
    byteBuff.rewind();
    byteBuff.put(pubkey);
    byteBuff.put(tweak);

    byte[][] retByteArray;
    r.lock();
    try {
        retByteArray = secp256k1_pubkey_tweak_mul(byteBuff, Secp256k1Context.getContext(), pubkey.length);
    } finally {
        r.unlock();
    }

    byte[] pubArr = retByteArray[0];

    int pubLen = (byte) new BigInteger(new byte[] { retByteArray[1][0] }).intValue() & 0xFF;
    int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue();

    assertEquals(pubArr.length, pubLen, "Got bad pubkey length.");

    assertEquals(retVal, 1, "Failed return value check.");

    return pubArr;
}
 
Example 12
Project: GLproject   File: PonitOrLines.java   View Source Code Vote up 5 votes
private void initVertexData() {
    vCount = 5;
    //顶点数据处理
    float[] vertices = new float[]{0, 0, 0,
                                   Constant.UNIT_SIZE, Constant.UNIT_SIZE, 0,
                                   -Constant.UNIT_SIZE, Constant.UNIT_SIZE, 0,
                                   -Constant.UNIT_SIZE, -Constant.UNIT_SIZE, 0,
                                   Constant.UNIT_SIZE, -Constant.UNIT_SIZE, 0};
    ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);
    vbb.order(ByteOrder.nativeOrder());
    mVertexBuffer = vbb.asFloatBuffer();
    mVertexBuffer.put(vertices)
                 .position(0);

    //颜色数据处理
    float[] colors = new float[]{
            //每个顶点的颜色RGBA
            1, 1, 0, 0,
            1, 1, 1, 0,
            0, 1, 0, 0,
            1, 1, 1, 0,
            1, 1, 0, 0};
    ByteBuffer cbb = ByteBuffer.allocateDirect(colors.length * 4);
    cbb.order(ByteOrder.nativeOrder());
    mColorBuffer = cbb.asFloatBuffer();
    mColorBuffer.put(colors)
                .position(0);

}
 
Example 13
Project: ApkMultiChannelPlugin   File: V1SchemeVerifier.java   View Source Code Vote up 5 votes
public static List<CentralDirectoryRecord> parseZipCentralDirectory(
        DataSource apk,
        ApkUtils.ZipSections apkSections)
                throws IOException, ApkFormatException {
    // Read the ZIP Central Directory
    long cdSizeBytes = apkSections.getZipCentralDirectorySizeBytes();
    if (cdSizeBytes > Integer.MAX_VALUE) {
        throw new ApkFormatException("ZIP Central Directory too large: " + cdSizeBytes);
    }
    long cdOffset = apkSections.getZipCentralDirectoryOffset();
    ByteBuffer cd = apk.getByteBuffer(cdOffset, (int) cdSizeBytes);
    cd.order(ByteOrder.LITTLE_ENDIAN);

    // Parse the ZIP Central Directory
    int expectedCdRecordCount = apkSections.getZipCentralDirectoryRecordCount();
    List<CentralDirectoryRecord> cdRecords = new ArrayList<>(expectedCdRecordCount);
    for (int i = 0; i < expectedCdRecordCount; i++) {
        CentralDirectoryRecord cdRecord;
        int offsetInsideCd = cd.position();
        try {
            cdRecord = CentralDirectoryRecord.getRecord(cd);
        } catch (ZipFormatException e) {
            throw new ApkFormatException(
                    "Malformed ZIP Central Directory record #" + (i + 1)
                            + " at file offset " + (cdOffset + offsetInsideCd),
                    e);
        }
        String entryName = cdRecord.getName();
        if (entryName.endsWith("/")) {
            // Ignore directory entries
            continue;
        }
        cdRecords.add(cdRecord);
    }
    // There may be more data in Central Directory, but we don't warn or throw because Android
    // ignores unused CD data.

    return cdRecords;
}
 
Example 14
Project: CoreX   File: RCONServer.java   View Source Code Vote up 5 votes
private void read(SelectionKey key) throws IOException {
    SocketChannel channel = (SocketChannel) key.channel();
    ByteBuffer buffer = ByteBuffer.allocate(4096);
    buffer.order(ByteOrder.LITTLE_ENDIAN);

    int bytesRead;
    try {
        bytesRead = channel.read(buffer);
    } catch (IOException exception) {
        key.cancel();
        channel.close();
        if (this.rconSessions.contains(channel)) {
            this.rconSessions.remove(channel);
        }
        if (this.sendQueues.containsKey(channel)) {
            this.sendQueues.remove(channel);
        }
        return;
    }

    if (bytesRead == -1) {
        key.cancel();
        channel.close();
        if (this.rconSessions.contains(channel)) {
            this.rconSessions.remove(channel);
        }
        if (this.sendQueues.containsKey(channel)) {
            this.sendQueues.remove(channel);
        }
        return;
    }

    buffer.flip();
    this.handle(channel, new RCONPacket(buffer));
}
 
Example 15
Project: elasticsearch_my   File: SystemCallFilter.java   View Source Code Vote up 5 votes
SockFProg(SockFilter filters[]) {
    len = (short) filters.length;
    // serialize struct sock_filter * explicitly, its less confusing than the JNA magic we would need
    Memory filter = new Memory(len * 8);
    ByteBuffer bbuf = filter.getByteBuffer(0, len * 8);
    bbuf.order(ByteOrder.nativeOrder()); // little endian
    for (SockFilter f : filters) {
        bbuf.putShort(f.code);
        bbuf.put(f.jt);
        bbuf.put(f.jf);
        bbuf.putInt(f.k);
    }
    this.filter = filter;
}
 
Example 16
Project: Nukkit-Java9   File: RCONPacket.java   View Source Code Vote up 5 votes
public ByteBuffer toBuffer() {
    ByteBuffer buffer = ByteBuffer.allocate(this.payload.length + 14);
    buffer.order(ByteOrder.LITTLE_ENDIAN);

    buffer.putInt(this.payload.length + 10);
    buffer.putInt(this.id);
    buffer.putInt(this.type);
    buffer.put(this.payload);

    buffer.put((byte) 0);
    buffer.put((byte) 0);

    buffer.flip();
    return buffer;
}
 
Example 17
Project: okwallet   File: ProtobufConnection.java   View Source Code Vote up 4 votes
@Override
public int receiveBytes(ByteBuffer buff) throws Exception {
    lock.lock();
    try {
        if (messageBytes != null) {
            // Just keep filling up the currently being worked on message
            int bytesToGet = Math.min(messageBytes.length - messageBytesOffset, buff.remaining());
            buff.get(messageBytes, messageBytesOffset, bytesToGet);
            messageBytesOffset += bytesToGet;
            if (messageBytesOffset == messageBytes.length) {
                // Filled up our buffer, decode the message
                deserializeMessage(ByteBuffer.wrap(messageBytes));
                messageBytes = null;
                if (buff.hasRemaining())
                    return bytesToGet + receiveBytes(buff);
            }
            return bytesToGet;
        }

        // If we cant read the length prefix yet, give up
        if (buff.remaining() < 4)
            return 0;

        // Read one integer in big endian
        buff.order(ByteOrder.BIG_ENDIAN);
        final int len = buff.getInt();

        // If length is larger than the maximum message size (or is negative/overflows) throw an exception and close the
        // connection
        if (len > maxMessageSize || len + 4 < 4)
            throw new IllegalStateException("Message too large or length underflowed");

        // If the buffer's capacity is less than the next messages length + 4 (length prefix), we must use messageBytes
        // as a temporary buffer to store the message
        if (buff.capacity() < len + 4) {
            messageBytes = new byte[len];
            // Now copy all remaining bytes into the new buffer, set messageBytesOffset and tell the caller how many
            // bytes we consumed
            int bytesToRead = buff.remaining();
            buff.get(messageBytes, 0, bytesToRead);
            messageBytesOffset = bytesToRead;
            return bytesToRead + 4;
        }

        if (buff.remaining() < len) {
            // Wait until the whole message is available in the buffer
            buff.position(buff.position() - 4); // Make sure the buffer's position is right at the end
            return 0;
        }

        // Temporarily limit the buffer to the size of the message so that the protobuf decode doesn't get messed up
        int limit = buff.limit();
        buff.limit(buff.position() + len);
        deserializeMessage(buff);
        checkState(buff.remaining() == 0);
        buff.limit(limit); // Reset the limit in case we have to recurse

        // If there are still bytes remaining, see if we can pull out another message since we won't get called again
        if (buff.hasRemaining())
            return len + 4 + receiveBytes(buff);
        else
            return len + 4;
    } finally {
        lock.unlock();
    }
}
 
Example 18
Project: openjdk-jdk10   File: ConnectorAddressLink.java   View Source Code Vote up 4 votes
private PerfHandle(ByteBuffer bb) {
    this.bb = bb.order(ByteOrder.nativeOrder());
}
 
Example 19
Project: GitHub   File: DefaultImageHeaderParser.java   View Source Code Vote up 4 votes
ByteBufferReader(ByteBuffer byteBuffer) {
  this.byteBuffer = byteBuffer;
  byteBuffer.order(ByteOrder.BIG_ENDIAN);
}
 
Example 20
Project: walle   File: PayloadWriter.java   View Source Code Vote up 3 votes
/**
 * put (id, String) into apk, update if id exists
 * @param apkFile apk file
 * @param id id
 * @param string string
 * @param lowMemory if need low memory operation, maybe a little slower
 * @throws IOException
 * @throws SignatureNotFoundException
 */
public static void put(final File apkFile, final int id, final String string, final boolean lowMemory) throws IOException, SignatureNotFoundException {
    final byte[] bytes = string.getBytes(ApkUtil.DEFAULT_CHARSET);
    final ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length);
    byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
    byteBuffer.put(bytes, 0, bytes.length);
    byteBuffer.flip();
    put(apkFile, id, byteBuffer, lowMemory);
}