github.com/geniusesgroup/libgo@v0.0.0-20220713101832-828057a9d3d4/binary/be-in-le-cpu.go (about)

     1  // For license and copyright information please see LEGAL file in 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 { return uint16(b[1]) | uint16(b[0])<<8 }
    15  func (bigEndian) Uint32(b []byte) uint32 {
    16  	return uint32(b[3]) | uint32(b[2])<<8 | uint32(b[1])<<16 | uint32(b[0])<<24
    17  }
    18  
    19  func (bigEndian) Uint64(b []byte) uint64 {
    20  	return uint64(b[7]) | uint64(b[6])<<8 | uint64(b[5])<<16 | uint64(b[4])<<24 |
    21  		uint64(b[3])<<32 | uint64(b[2])<<40 | uint64(b[1])<<48 | uint64(b[0])<<56
    22  }
    23  
    24  func (bigEndian) PutUint16(b []byte, v uint16) {
    25  	b[0] = byte(v >> 8)
    26  	b[1] = byte(v)
    27  }
    28  func (bigEndian) PutUint32(b []byte, v uint32) {
    29  	b[0] = byte(v >> 24)
    30  	b[1] = byte(v >> 16)
    31  	b[2] = byte(v >> 8)
    32  	b[3] = byte(v)
    33  }
    34  func (bigEndian) PutUint64(b []byte, v uint64) {
    35  	b[0] = byte(v >> 56)
    36  	b[1] = byte(v >> 48)
    37  	b[2] = byte(v >> 40)
    38  	b[3] = byte(v >> 32)
    39  	b[4] = byte(v >> 24)
    40  	b[5] = byte(v >> 16)
    41  	b[6] = byte(v >> 8)
    42  	b[7] = byte(v)
    43  }
    44  
    45  func init() {
    46  	i := uint32(1)
    47  	b := (*[4]byte)(unsafe.Pointer(&i))
    48  	if b[0] != 1 {
    49  		panic("Expect LittleEndian CPU but have BigEndian CPU that cause many problem in other packages")
    50  	}
    51  }