大端模式、小端模式解析

大端模式、小端模式

计算机内存按字节编址,每个地址的存储单元可以存放8bit的数据。大小端面向多字节类型定义,比如2字节、4字节、8字节整型、长整型、浮点型等,单字节一般不用考虑。

查看当前机器大小端模式

各变成语言有不同的实现,Java可以通过如下代码获取当前机器的大小端模式

1
2
// java.nio包下的ByteOrder类
ByteOrder.nativeOrder();

大端模式

低地址存放高字节,高地址存放低字节。即将数据的低位放在高地址,高位放在低地址中

例:Java中一个int类型数据0x0000007f(十进制为127),4个字节,32位,7f为最低字节,其大端存储为

big-endian

小端模式

低地址存放低字节,高地址存放高字节。即将数据的低位放在低地址,高位放在高地址中

例:Java中一个int类型数据0x0000007f(十进制为127),4个字节,32位,7f为最低字节,其小端存储为

little-endian

代码示例

int类型数据转换为字节数组

程序代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* 00000000 00000000 00000000 01111111
*/
private static final int BASE_NUM = 0x0000007f;

public static void int2BytesTest() {
int2Bytes(BASE_NUM, ByteOrder.BIG_ENDIAN);
int2Bytes(BASE_NUM, ByteOrder.LITTLE_ENDIAN);
}

/**
* int转byte数组(ByteBuffer默认为大端)
*
* @param num int num
* @param byteOrder 排序规则
*/
public static void int2Bytes(int num, ByteOrder byteOrder) {
final ByteBuffer byteBuffer = ByteBuffer.allocate(4);
byteBuffer.order(byteOrder);
byte[] array = byteBuffer.putInt(num).array();
System.out.println("input:" + num + ", byteOrder:" + byteOrder + ", result:" + Arrays.toString(array));
}

输出结果

1
2
input:127, byteOrder:BIG_ENDIAN, result:[0, 0, 0, 127]
input:127, byteOrder:LITTLE_ENDIAN, result:[127, 0, 0, 0]

字节数组转int

还是以0x0000007f为例,程序代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* 00000000 00000000 00000000 01111111
*/
private static final int BASE_NUM = 0x0000007f;

public static void bytes2IntTest() {
// BIG_ENDIAN
byte[] input1 = new byte[]{0, 0, 0, 127};
bytes2Int(input1, ByteOrder.BIG_ENDIAN);
bytes2Int(input1, ByteOrder.LITTLE_ENDIAN);
// LITTLE_ENDIAN
byte[] input2 = new byte[]{127, 0, 0, 0};
bytes2Int(input2, ByteOrder.BIG_ENDIAN);
bytes2Int(input2, ByteOrder.LITTLE_ENDIAN);
}

/**
* bytes数组转int(ByteBuffer默认为大端)
*
* @param input 数组
* @param byteOrder 排序规则
*/
private static void bytes2Int(byte[] input, ByteOrder byteOrder) {
ByteBuffer byteBuffer = ByteBuffer.wrap(input, 0, 4);
byteBuffer.order(byteOrder);
int result = byteBuffer.getInt();
System.out.println("input:" + Arrays.toString(input) + ", byteOrder:" + byteOrder + ", result:" + result);
}

输出结果

1
2
3
4
input:[0, 0, 0, 127], byteOrder:BIG_ENDIAN, result:127
input:[0, 0, 0, 127], byteOrder:LITTLE_ENDIAN, result:2130706432
input:[127, 0, 0, 0], byteOrder:BIG_ENDIAN, result:2130706432
input:[127, 0, 0, 0], byteOrder:LITTLE_ENDIAN, result:127
文章作者: DongyangHu
文章链接: http://hudongyang.com/2021/02/25/big-little-endian/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Sunshine