NIO – Endian代码示例

package player.kent.chen.temp.learnnio;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class PlayEndian {

    public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.wrap(new byte[20]);
        buffer.asCharBuffer().put("12345");
        printBufferAsArray(buffer); //1, 打印0 49 0 50 0 51 ...

        buffer.rewind(); //让buffer的位置移到最前        
        buffer.order(ByteOrder.BIG_ENDIAN);
        buffer.asCharBuffer().put("12345");
        printBufferAsArray(buffer); //2, 打印结果将和#1一样,因为java默认的byte order就big endian

        buffer.rewind();
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        buffer.asCharBuffer().put("12345");
        printBufferAsArray(buffer); //3,打印49 0 50 0 51 0 ...

    }

    private static void printBufferAsArray(ByteBuffer buffer) {
        for (byte b : buffer.array()) {
            System.out.print(b + " ");
        }
        System.out.println();
    }

}

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.