[Java]ByteBuffer的用处

ByteBuffer 的用处: 对一个byte buffer 可以进行按short,int等读取,读取位置自动增加。 这样可以完成对一个byte buffer的基本解析。 其中order()会影响对short,int的解释生成,是little endian, 还是Big endian?

以下是一个例子:


    private String waitSocketSignal(InputStream is) throws IOException {
    byte [] sig = new byte[SOCK_SIGNAL_SIZE];
    int ret = readAll(is, sig);
    if (VDBG) Log.d(TAG, "waitSocketSignal read 16 bytes signal ret: " + ret);
    ByteBuffer bb = ByteBuffer.wrap(sig);
    bb.order(ByteOrder.nativeOrder());
    int size = bb.getShort();
    if(size != SOCK_SIGNAL_SIZE)
        throw new IOException("Connection failure, wrong signal size: " + size);
    byte [] addr = new byte[6];
    bb.get(addr);
    int channel = bb.getInt();
    int status = bb.getInt();
    String RemoteAddr = convertAddr(addr);
    if (VDBG) Log.d(TAG, "waitSocketSignal: sig size: " + size + ", remote addr: "
            + RemoteAddr + ", channel: " + channel + ", status: " + status);
    if(status != 0)
        throw new IOException("Connection failure, status: " + status);
    return RemoteAddr;
}

你可能感兴趣的:([Java]ByteBuffer的用处)