Created
May 31, 2017 14:55
-
-
Save linux4life798/fbc5e36912dbe52d85fbd1193ccfa386 to your computer and use it in GitHub Desktop.
Validate large HEX strings in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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