Go: Parse decimal integers within an explicit signed range
A value destined for a signed 16-bit field should be checked against that range while parsing. strconv.ParseInt accepts an explicit base and bit size, even though its result has type int64.
Set up
Tested on Linux with Go 1.26.10. Use Bash with Go on your PATH. Keep the same terminal through cleanup, and stop if setup fails.
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Run the example
Save as parseint_explicit_range.go:
package main
import (
"errors"
"fmt"
"strconv"
)
func main() {
for _, input := range []string{"32767", "32768", "-32768", "-32769", "010", "0x10", "12x"} {
n, err := strconv.ParseInt(input, 10, 16)
switch {
case errors.Is(err, strconv.ErrRange):
fmt.Printf("%q: rejected range\n", input)
case err != nil:
fmt.Printf("%q: rejected syntax\n", input)
default:
value := int16(n)
fmt.Printf("%q: accepted %d\n", input, value)
}
}
}go run parseint_explicit_range.goObserved output:
"32767": accepted 32767
"32768": rejected range
"-32768": accepted -32768
"-32769": rejected range
"010": accepted 10
"0x10": rejected syntax
"12x": rejected syntaxRead the result
The boundary values succeed; the neighboring values fail before conversion. Explicit base 10 makes 010 decimal ten and rejects the hexadecimal prefix. A range error can accompany a saturated numeric result, so consuming the value while ignoring the error would lose the rejection.
Apply it carefully
The fixed base and bit size make the remaining errors syntax errors in this example. Base zero instead recognizes prefixes and permits underscores; choose it only if that grammar is intended. Domain rules, such as requiring a positive count, still need a separate check after parsing.
See the Go standard-library reference.
Clean up
Remove the source and the empty scratch directory. Go may retain build-cache files outside this directory. If the directory is not empty, inspect its contents before removing anything else.
rm -- parseint_explicit_range.go
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirAcknowledgements
This post was created with assistance from AI.