github.com/GeniusesGroup/libgo@v0.0.0-20220929090155-5ff932cb408e/binary/be-in-le-cpu.go (about) 1 // For license and copyright information please see the LEGAL file in the code repository 2 3 //go:build 386 || amd64 || amd64p32 || arm || arm64 || loong64 || mips64le || mips64p32le || mipsle || ppc64le || riscv || riscv64 || wasm 4 5 package binary 6 7 import "unsafe" 8 9 // BigEndian is the big-endian implementation to get|set from be binary to le cpu 10 var BigEndian bigEndian 11 12 type bigEndian struct{} 13 14 func (bigEndian) Uint16(b []byte) uint16 { 15 _ = b[1] // bounds check hint to compiler; see golang.org/issue/14808 16 return uint16(b[1]) | uint16(b[0])<<8 17 } 18 func (bigEndian) Uint32(b []byte) uint32 { 19 _ = b[3] // bounds check hint to compiler; see golang.org/issue/14808 20 return uint32(b[3]) | uint32(b[2])<<8 | uint32(b[1])<<16 | uint32(b[0])<<24 21 } 22 23 func (bigEndian) Uint64(b []byte) uint64 { 24 _ = b[7] // bounds check hint to compiler; see golang.org/issue/14808 25 return uint64(b[7]) | uint64(b[6])<<8 | uint64(b[5])<<16 | uint64(b[4])<<24 | 26 uint64(b[3])<<32 | uint64(b[2])<<40 | uint64(b[1])<<48 | uint64(b[0])<<56 27 } 28 29 func (bigEndian) PutUint16(b []byte, v uint16) { 30 _ = b[1] // early bounds check to guarantee safety of writes below 31 b[0] = byte(v >> 8) 32 b[1] = byte(v) 33 } 34 func (bigEndian) PutUint32(b []byte, v uint32) { 35 _ = b[3] // early bounds check to guarantee safety of writes below 36 b[0] = byte(v >> 24) 37 b[1] = byte(v >> 16) 38 b[2] = byte(v >> 8) 39 b[3] = byte(v) 40 } 41 func (bigEndian) PutUint64(b []byte, v uint64) { 42 _ = b[7] // early bounds check to guarantee safety of writes below 43 b[0] = byte(v >> 56) 44 b[1] = byte(v >> 48) 45 b[2] = byte(v >> 40) 46 b[3] = byte(v >> 32) 47 b[4] = byte(v >> 24) 48 b[5] = byte(v >> 16) 49 b[6] = byte(v >> 8) 50 b[7] = byte(v) 51 } 52 53 func init() { 54 i := uint32(1) 55 b := (*[4]byte)(unsafe.Pointer(&i)) 56 if b[0] != 1 { 57 panic("Expect LittleEndian CPU but have BigEndian CPU that cause many problem in other packages") 58 } 59 }