Skip to content

Instantly share code, notes, and snippets.

@linux4life798
Created May 31, 2017 14:55
Show Gist options
  • Save linux4life798/fbc5e36912dbe52d85fbd1193ccfa386 to your computer and use it in GitHub Desktop.
Save linux4life798/fbc5e36912dbe52d85fbd1193ccfa386 to your computer and use it in GitHub Desktop.
Validate large HEX strings in Go
// isValidHex indicates if value is a proper hex strings that can be contained
// with the given number of bits
func isValidHex(value string, bits int) bool {
str := strings.ToLower(value)
precZeros := true
bitcount := 0
for _, c := range str {
// Ensure the rune is a HEX character
if !strings.Contains("0123456789abcdef", string(c)) {
return false
}
// Ensure that we are within the given bit size
if precZeros {
value, err := strconv.ParseInt(string(c), 16, 8)
if err != nil {
// This is unclear how this could ever error out
fmt.Println("err on parse")
return false
}
// Add in variable number of bits for first HEX char
if value == 0 {
continue
} else {
precZeros = false
}
bitcount += int(math.Ceil(math.Log2(float64(value + 1))))
} else {
// Add in a nibble
bitcount += 4
}
if bitcount > bits {
return false
}
}
return true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment