github.com/yinchengtsinghua/golang-Eos-dpos-Ethereum@v0.0.0-20190121132951-92cc4225ed8e/common/bytes.go (about) 1 2 //此源码被清华学神尹成大魔王专业翻译分析并修改 3 //尹成QQ77025077 4 //尹成微信18510341407 5 //尹成所在QQ群721929980 6 //尹成邮箱 yinc13@mails.tsinghua.edu.cn 7 //尹成毕业于清华大学,微软区块链领域全球最有价值专家 8 //https://mvp.microsoft.com/zh-cn/PublicProfile/4033620 9 //版权所有2014 Go Ethereum作者 10 // 11 // 12 //Go-Ethereum库是免费软件:您可以重新分发它和/或修改 13 //根据GNU发布的较低通用公共许可证的条款 14 //自由软件基金会,或者许可证的第3版,或者 15 //(由您选择)任何更高版本。 16 // 17 //Go以太坊图书馆的发行目的是希望它会有用, 18 //但没有任何保证;甚至没有 19 //适销性或特定用途的适用性。见 20 //GNU较低的通用公共许可证,了解更多详细信息。 21 // 22 //你应该收到一份GNU较低级别的公共许可证副本 23 //以及Go以太坊图书馆。如果没有,请参见<http://www.gnu.org/licenses/>。 24 25 //package common包含各种助手函数。 26 package common 27 28 import "encoding/hex" 29 30 //tohex返回b的十六进制表示形式,前缀为“0x”。 31 //对于空切片,返回值为“0x0”。 32 // 33 //已弃用:请改用hexutil.encode。 34 func ToHex(b []byte) string { 35 hex := Bytes2Hex(b) 36 if len(hex) == 0 { 37 hex = "0" 38 } 39 return "0x" + hex 40 } 41 42 //FromHex返回十六进制字符串s表示的字节。 43 //s的前缀可以是“0x”。 44 func FromHex(s string) []byte { 45 if len(s) > 1 { 46 if s[0:2] == "0x" || s[0:2] == "0X" { 47 s = s[2:] 48 } 49 } 50 if len(s)%2 == 1 { 51 s = "0" + s 52 } 53 return Hex2Bytes(s) 54 } 55 56 //CopyBytes返回所提供字节的精确副本。 57 func CopyBytes(b []byte) (copiedBytes []byte) { 58 if b == nil { 59 return nil 60 } 61 copiedBytes = make([]byte, len(b)) 62 copy(copiedBytes, b) 63 64 return 65 } 66 67 //hashexprefix验证str以“0x”或“0x”开头。 68 func hasHexPrefix(str string) bool { 69 return len(str) >= 2 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X') 70 } 71 72 //IShexCharacter返回C的bool作为有效的十六进制。 73 func isHexCharacter(c byte) bool { 74 return ('0' <= c && c <= '9') || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F') 75 } 76 77 // 78 func isHex(str string) bool { 79 if len(str)%2 != 0 { 80 return false 81 } 82 for _, c := range []byte(str) { 83 if !isHexCharacter(c) { 84 return false 85 } 86 } 87 return true 88 } 89 90 //bytes2hex返回d的十六进制编码。 91 func Bytes2Hex(d []byte) string { 92 return hex.EncodeToString(d) 93 } 94 95 //hex2bytes返回十六进制字符串str表示的字节。 96 func Hex2Bytes(str string) []byte { 97 h, _ := hex.DecodeString(str) 98 return h 99 } 100 101 //hex2bytesfixed返回指定固定长度flen的字节。 102 func Hex2BytesFixed(str string, flen int) []byte { 103 h, _ := hex.DecodeString(str) 104 if len(h) == flen { 105 return h 106 } 107 if len(h) > flen { 108 return h[len(h)-flen:] 109 } 110 hh := make([]byte, flen) 111 copy(hh[flen-len(h):flen], h[:]) 112 return hh 113 } 114 115 // 116 func RightPadBytes(slice []byte, l int) []byte { 117 if l <= len(slice) { 118 return slice 119 } 120 121 padded := make([]byte, l) 122 copy(padded, slice) 123 124 return padded 125 } 126 127 //LeftPadBytes将零个焊盘向左切片至长度L。 128 func LeftPadBytes(slice []byte, l int) []byte { 129 if l <= len(slice) { 130 return slice 131 } 132 133 padded := make([]byte, l) 134 copy(padded[l-len(slice):], slice) 135 136 return padded 137 }