大端序小端序

摘自《Linux内核编程》

大端序就是指:最高位字节存储在低地址空间,最低位字节存储在随后的3个地址空间中(以32位数据而言)。

小端序和大端序相反:最低位字节存储在地地址空间,最高位字节存储在随后的三个地址空间中(以32位数据而言)。

比如看这个:十六进制数0x12345678的表示:

32位大端序表示
12345678
81624

 

32位小端表示
78563412
081624

 

 

 

 

 

 

备注:0x12345678中 12 是高位,78是低位。

x86体系结构是用小端序。

编程查看自己电脑是大端还是小端:

1 int a = 1;
2 printf("sizeof int : %d\n",sizeof(int));
3 printf("是大端序吗? %c\n",((char*)&a)[sizeof(int)-1]==1?'y':'n');

代码改自:《大端序,小端序》 这里有详细解释,不再赘述。

 

 

转载于:https://www.cnblogs.com/iceseal/p/3603470.html

### Java 中实现 `int` 类型大端小端序互转 在计算机科学中,“大端”和“小端”的概念用于描述多字节值的存储方式[^2]。对于Java中的`int`类型数据,可以通过运算来完成大小端之间的转换。 #### 方法一:通过移操作手动交换字节置 这种方法利用了按逻辑运算符以及左移右移指令,可以精确控制每一个字节的置: ```java public class EndianConverter { public static int bigEndianToInt(byte[] bytes, int offset) { return ((bytes[offset++] & 0xFF) << 24) | ((bytes[offset++] & 0xFF) << 16) | ((bytes[offset++] & 0xFF) << 8 ) | (bytes[offset ] & 0xFF); } public static byte[] intToBigEndian(int value){ return new byte[]{ (byte)((value >>> 24) & 0xFF), (byte)((value >>> 16) & 0xFF), (byte)((value >>> 8) & 0xFF), (byte)( value & 0xFF) }; } public static int littleEndianToInt(byte[] bytes, int offset) { return (bytes[offset ] & 0xFF) | ((bytes[offset + 1] & 0xFF) << 8 ) | ((bytes[offset + 2] & 0xFF) << 16) | ((bytes[offset + 3] & 0xFF) << 24); } public static byte[] intToLittleEndian(int value){ return new byte[]{ (byte)( value & 0xFF), (byte)((value >>> 8) & 0xFF), (byte)((value >>> 16) & 0xFF), (byte)((value >>> 24) & 0xFF) }; } } ``` 上述代码展示了如何将一个整数值编码成不同字节格式下的字节数组,同时也提供了反向解码的功能。这里需要注意的是,在处理单个字节时要使用无符号右移(`>>>`)以确保高补零而非复制符号[^1]。 #### 方法二:借助 ByteBuffer 和 ByteOrder API 除了手工编写转换函数外,还可以利用JDK自带的工具类ByteBuffer配合ByteOrder枚举来进行更加简洁的操作: ```java import java.nio.ByteBuffer; import java.nio.ByteOrder; // ... private static final int VALUE = 0x1A2B3C4D; // example integer value // Convert from host to network(big-endian) order using ByteBuffer and ByteOrder ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES).order(ByteOrder.BIG_ENDIAN).putInt(VALUE); buffer.rewind(); // Reset position back to zero before reading data out. System.out.println("Original Value as Big endian: " + Integer.toHexString(buffer.getInt())); // Change the byte order of existing Buffer instance without reallocating memory space buffer.order(ByteOrder.LITTLE_ENDIAN).rewind(); System.out.println("Same Value but Little endian: " + Integer.toHexString(buffer.getInt())); ``` 这段程首先创建了一个固定长度为4字节(即等于Integer类型的宽度)的缓冲区,并指定了初始字节模式为大端。接着改变此实例内部的状态使之采用相反的小端排列读取相同的数据流,从而实现了两种形式间的切换。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值