go語言大端模式和小端模式

 閱讀大約需要1分鐘

go語言大端模式和小端模式

什麼是大端和小端?

Big-Endian和Little-Endian的定義如下:

  1. Little-Endian就是低位字節排放在內存的低地址端,高位字節排放在內存的高地址端。

  2. Big-Endian就是高位字節排放在內存的低地址端,低位字節排放在內存的高地址端。

例如十進制258,十六進制值為0x0102在內存中的表示形式為:

1)大端模式:

低地址 —————–> 高地址

0x01 | 0x02

2)小端模式:

低地址 ——————> 高地址

0x02 | 0x01

go語言代碼如下:

package main
import (
	"encoding/binary"
	"fmt"
)

func BigEndian() {
	// 大端序
	var testInt int32 = 0x0102
	fmt.Printf("%d use big endian: \n", testInt)

	var testBytes = make([]byte, 4)
	binary.BigEndian.PutUint32(testBytes, uint32(testInt))
	fmt.Println("int32 to bytes:", testBytes)

	convInt := binary.BigEndian.Uint32(testBytes)
	fmt.Printf("bytes to int32: %d\n\n", convInt)
}

func LittleEndian() {
	// 小端序
	var testInt int32 = 0x0102
	fmt.Printf("%d use little endian: \n", testInt)

	var testBytes = make([]byte, 4)
	binary.LittleEndian.PutUint32(testBytes, uint32(testInt))
	fmt.Println("int32 to bytes:", testBytes)

	convInt := binary.LittleEndian.Uint32(testBytes)
	fmt.Printf("bytes to int32: %d\n\n", convInt)
}

func main() {
	BigEndian()
	LittleEndian()
}

運行結果如下:

258 use big endian: 
int32 to bytes: [0 0 1 2]
bytes to int32: 258

258 use little endian: 
int32 to bytes: [2 1 0 0]
bytes to int32: 258

正如定義的一樣,大端模式高位字節(0x00,0x00)排放在內存的低地址端(b[0],b[1]),低位字節(0x01,0x02)排放在內存的高地址端(b[2],b[3])。

小端模式高位字節(0x00,0x00)排放在內存的高地址端(b[2],b[3]),低位字節(0x02,0x01)排放在內存的低地址端(b[0],b[1])。

在計算機內部,小端序被廣泛應用於現代性CPU內部存儲數據,而在其他場景例如網絡傳輸和文件存儲使用大端序。

在網絡協議層操作二進制數字時約定使用大端序,大端序是網絡字節傳輸採用的方式。