Go language determines whether the system is big-endian or little-endian

 1 minute to read

The go language determines whether the system is big-endian or little-endian

package main

import (
	"encoding/binary"
	"fmt"
	"unsafe"
)

const intWidth = unsafe.Sizeof(0)

var byteOrder binary.ByteOrder

func main() {
	var a = 1
	if v := (*[intWidth]byte)(unsafe.Pointer(&a)); v[0] == 0 {
		byteOrder = binary.BigEndian
	} else {
		byteOrder = binary.LittleEndian
	}
	fmt.Println(intWidth)
	v1 := (*[intWidth]byte)(unsafe.Pointer(&a))
	fmt.Println(*v1)
	fmt.Println(byteOrder)
}

The results are as follows:

8
[1 0 0 0 0 0 0 0]
LittleEndian

unsafe.Sizeof(0) checks the size of the space occupied by the int type and the result is 8, that is, an int type occupies 8 bytes.

Int type variable a=1, then convert a into a byte array, you can see the storage of variable a in the byte array v[0]=1, it can be judged that the int type variable a is stored in little endian in the system, that is, the low-order byte is stored at the starting address, Because the value is a=1, the hexadecimal representation is 00 00 00 00 00 00 00 01, the low order is 01, and the decimal is 1, but in Byte storage is placed at the starting address, so it belongs to little endian storage.