Go language big endian mode and little endian mode

 2 minutes to read

go language big endian mode and little endian mode

What are big endian and little endian?

Big-Endian and Little-Endian are defined as follows:

  1. Little-Endian means that the low-order bytes are placed at the low address end of the memory, and the high-order bytes are placed at the high address end of the memory.

  2. Big-Endian means that the high-order bytes are placed at the low address end of the memory, and the low-order bytes are placed at the high address end of the memory.

For example, decimal 258, the hexadecimal value 0x0102 is represented in memory as:

  1. Big endian mode:

low address —————–> high address

0x01 | 0x02

  1. Little endian mode:

Low address ——————> High address

0x02 | 0x01

The go language code is as follows:

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()
}

The results are as follows:

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

As defined, the high-order byte (0x00, 0x00) of the big endian mode is discharged at the low-address end (b[0], b[1]) of the memory, and the low-order byte (0x01, 0x02) is discharged at the high-end address of the memory (b[2],b[3]).

In little-endian mode, the high-order byte (0x00, 0x00) is discharged at the high address end of the memory (b[2], b[3]), and the low-order byte (0x02, 0x01) is discharged at the low address end of the memory (b[0] ,b[1]).

Inside computers, little-endian is widely used to store data inside modern CPUs, while big-endian is used in other scenarios such as network transfers and file storage.

When operating binary numbers at the network protocol layer, it is agreed to use big endian, which is the method used for network byte transmission.