github.com/status-im/status-go@v1.1.0/eth-node/types/bytes.go (about)

     1  package types
     2  
     3  import "encoding/hex"
     4  
     5  // has0xPrefix validates str begins with '0x' or '0X'.
     6  func has0xPrefix(str string) bool {
     7  	return len(str) >= 2 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X')
     8  }
     9  
    10  // isHexCharacter returns bool of c being a valid hexadecimal.
    11  func isHexCharacter(c byte) bool {
    12  	return ('0' <= c && c <= '9') || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F')
    13  }
    14  
    15  // isHex validates whether each byte is valid hexadecimal string.
    16  func isHex(str string) bool {
    17  	if len(str)%2 != 0 {
    18  		return false
    19  	}
    20  	for _, c := range []byte(str) {
    21  		if !isHexCharacter(c) {
    22  			return false
    23  		}
    24  	}
    25  	return true
    26  }
    27  
    28  // Bytes2Hex returns the hexadecimal encoding of d.
    29  func Bytes2Hex(d []byte) string {
    30  	return hex.EncodeToString(d)
    31  }
    32  
    33  // Hex2Bytes returns the bytes represented by the hexadecimal string str.
    34  func Hex2Bytes(str string) []byte {
    35  	if has0xPrefix(str) {
    36  		str = str[2:]
    37  	}
    38  
    39  	h, _ := hex.DecodeString(str)
    40  	return h
    41  }
    42  
    43  // ToHex returns the hex string representation of bytes with 0x prefix.
    44  func ToHex(bytes []byte) string {
    45  	return "0x" + Bytes2Hex(bytes)
    46  }