Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to verify if string represents a hex number in go

Tags:

go

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

like image 989
Ben Lieber Avatar asked Dec 29 '17 19:12

Ben Lieber


1 Answers

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
}
like image 120
Bayta Darell Avatar answered Nov 15 '22 07:11

Bayta Darell