Last active
July 25, 2022 12:44
-
-
Save rsperl/345b32290a373dc014e3d6a204544fc8 to your computer and use it in GitHub Desktop.
byteorder operations #go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var nativeEndian binary.ByteOrder | |
func setByteOrder() { | |
buf := [2]byte{} | |
*(*uint16)(unsafe.Pointer(&buf[0])) = uint16(0xABCD) | |
switch buf { | |
case [2]byte{0xCD, 0xAB}: | |
nativeEndian = binary.LittleEndian | |
case [2]byte{0xAB, 0xCD}: | |
nativeEndian = binary.BigEndian | |
default: | |
panic("Could not determine native endianness.") | |
} | |
} | |
func isLittleEndian() bool { | |
if nativeEndian == nil { | |
setByteOrder() | |
} | |
return nativeEndian == binary.LittleEndian | |
} | |
func littleEndianToDecimal(b []byte) int { | |
return int(nativeEndian.Uint64(b)) | |
} | |
func bytesToHex(b []byte) string { | |
return hex.EncodeToString(b) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment