This mostly works:
import "encoding/hex"
func isHexString(s string) bool {
_, err := hex.DecodeString(s)
return err == nil
}
However, we also may want to support odd length hex strings. Checking against hex.ErrLength doesn't work because this error precedes whether the string contains hex characters. I guess could manipulate string to contain the appropriate number of characters and apply both checks but it seems like there should be better way.
https://golang.org/pkg/encoding/hex/#DecodeString
If your goal is to parse the hex digits as a integer or unsigned integer, then call strconv.ParseInt or strconv.ParseUint:
n, err := strconv.ParseUint(s, 16, 64)
if err != nil {
// s is not a valid
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With