2019-11-23 17:57:05 +00:00
|
|
|
package types
|
|
|
|
|
|
|
|
import "encoding/hex"
|
|
|
|
|
|
|
|
// has0xPrefix validates str begins with '0x' or '0X'.
|
|
|
|
func has0xPrefix(str string) bool {
|
|
|
|
return len(str) >= 2 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X')
|
|
|
|
}
|
|
|
|
|
|
|
|
// isHexCharacter returns bool of c being a valid hexadecimal.
|
|
|
|
func isHexCharacter(c byte) bool {
|
|
|
|
return ('0' <= c && c <= '9') || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F')
|
|
|
|
}
|
|
|
|
|
|
|
|
// isHex validates whether each byte is valid hexadecimal string.
|
|
|
|
func isHex(str string) bool {
|
|
|
|
if len(str)%2 != 0 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
for _, c := range []byte(str) {
|
|
|
|
if !isHexCharacter(c) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
// Bytes2Hex returns the hexadecimal encoding of d.
|
|
|
|
func Bytes2Hex(d []byte) string {
|
|
|
|
return hex.EncodeToString(d)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Hex2Bytes returns the bytes represented by the hexadecimal string str.
|
|
|
|
func Hex2Bytes(str string) []byte {
|
2021-10-26 10:48:02 +00:00
|
|
|
if has0xPrefix(str) {
|
|
|
|
str = str[2:]
|
|
|
|
}
|
|
|
|
|
2019-11-23 17:57:05 +00:00
|
|
|
h, _ := hex.DecodeString(str)
|
|
|
|
return h
|
|
|
|
}
|
2023-10-24 20:17:02 +00:00
|
|
|
|
|
|
|
// ToHex returns the hex string representation of bytes with 0x prefix.
|
|
|
|
func ToHex(bytes []byte) string {
|
|
|
|
return "0x" + Bytes2Hex(bytes)
|
|
|
|
}
|