github.com/neatlab/neatio@v1.7.3-0.20220425043230-d903e92fcc75/utilities/common/bytes.go (about) 1 package common 2 3 import ( 4 "encoding/binary" 5 "encoding/hex" 6 "unsafe" 7 ) 8 9 func ToHex(b []byte) string { 10 hex := Bytes2Hex(b) 11 12 if len(hex) == 0 { 13 hex = "0" 14 } 15 return "0x" + hex 16 } 17 18 func FromHex(s string) []byte { 19 if len(s) > 1 { 20 if s[0:2] == "0x" || s[0:2] == "0X" { 21 s = s[2:] 22 } 23 } 24 if len(s)%2 == 1 { 25 s = "0" + s 26 } 27 return Hex2Bytes(s) 28 } 29 30 func CopyBytes(b []byte) (copiedBytes []byte) { 31 if b == nil { 32 return nil 33 } 34 copiedBytes = make([]byte, len(b)) 35 copy(copiedBytes, b) 36 37 return 38 } 39 40 func hasHexPrefix(str string) bool { 41 return len(str) >= 2 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X') 42 } 43 44 func isHexCharacter(c byte) bool { 45 return ('0' <= c && c <= '9') || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F') 46 } 47 48 func isHex(str string) bool { 49 if len(str)%2 != 0 { 50 return false 51 } 52 for _, c := range []byte(str) { 53 if !isHexCharacter(c) { 54 return false 55 } 56 } 57 return true 58 } 59 60 func Bytes2Hex(d []byte) string { 61 return hex.EncodeToString(d) 62 } 63 64 func Hex2Bytes(str string) []byte { 65 h, _ := hex.DecodeString(str) 66 67 return h 68 } 69 70 func Hex2BytesFixed(str string, flen int) []byte { 71 h, _ := hex.DecodeString(str) 72 if len(h) == flen { 73 return h 74 } else { 75 if len(h) > flen { 76 return h[len(h)-flen:] 77 } else { 78 hh := make([]byte, flen) 79 copy(hh[flen-len(h):flen], h[:]) 80 return hh 81 } 82 } 83 } 84 85 func RightPadBytes(slice []byte, l int) []byte { 86 if l <= len(slice) { 87 return slice 88 } 89 90 padded := make([]byte, l) 91 copy(padded, slice) 92 93 return padded 94 } 95 96 func LeftPadBytes(slice []byte, l int) []byte { 97 if l <= len(slice) { 98 return slice 99 } 100 101 padded := make([]byte, l) 102 copy(padded[l-len(slice):], slice) 103 104 return padded 105 } 106 107 const INT_SIZE int = int(unsafe.Sizeof(0)) 108 109 func isBigEndian() bool { 110 var i int = 0x1 111 bs := (*[INT_SIZE]byte)(unsafe.Pointer(&i)) 112 if bs[0] == 0 { 113 return false 114 } 115 116 return true 117 } 118 119 func Bytes2Uint64(b []byte) uint64 { 120 121 data := []byte{0, 0, 0, 0, 0, 0, 0, 0} 122 blen := len(b) 123 124 for i := 1; i <= blen; i++ { 125 data[8-i] = b[len(b)-i] 126 } 127 128 if isBigEndian() { 129 return binary.BigEndian.Uint64(data) 130 } else { 131 return binary.LittleEndian.Uint64(data) 132 } 133 }