← 中文资源

简体中文版本

ByteBuffer 视图与字节序

asIntBuffer 这类视图按当前 ByteOrder 解释同一组字节:大端与小端读出的整数完全不同,跨协议交换二进制数据前必须显式统一字节序。

阅读英文原文

实现说明

整个示例围绕类 ProtocolFrames和函数 main组织。

使用要点

  • 跑完文件,输出里会留下标记——bytes:、as big-endian int:、as little-endian int:。

常见问题

运行「ByteBuffer 视图与字节序」会打印什么?

运行文件本身,bytes:、as big-endian int:、as little-endian int: 这些前缀各对应一段演示逻辑。

核心语句

frame.order(ByteOrder.BIG_ENDIAN); // writer lays out multi-byte fields big-endian
frame.putInt(0x01020304);
ByteBuffer little = frame.duplicate().order(ByteOrder.LITTLE_ENDIAN);
frame.get(head); // relative read advances the position
System.out.println("bytes: " + HexFormat.of().formatHex(head));

代码示例

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.HexFormat;

public class ProtocolFrames {

    public static void main(String[] args) {
        ByteBuffer frame = ByteBuffer.allocate(8);
        frame.order(ByteOrder.BIG_ENDIAN); // writer lays out multi-byte fields big-endian
        frame.putInt(0x01020304);
        frame.putShort((short) 0x0506);

        frame.flip();
        byte[] head = new byte[4];
        frame.get(head); // relative read advances the position
        System.out.println("bytes: " + HexFormat.of().formatHex(head));

        // Views interpret the same bytes under the current ByteOrder
        frame.rewind();
        System.out.println("as big-endian int:    " + frame.getInt());
        ByteBuffer little = frame.duplicate().order(ByteOrder.LITTLE_ENDIAN);
        System.out.println("as little-endian int: " + little.getInt());
    }
}