TheAlgorithms/Go · error
binary number must be in range 0 to 2^(31-1)
Error message
binary number must be in range 0 to 2^(31-1)
What it means
BinaryToDecimal limits input to at most 32 characters so the accumulated value fits in a 32-bit signed integer range (0 to 2^31-1). Longer strings would overflow the int result on 32-bit platforms, so the function rejects them up front. The error is created ad-hoc via errors.New.
Source
Thrown at conversion/binarytodecimal.go:32
package conversion
// Importing necessary package.
import (
"errors"
"regexp"
)
var isValid = regexp.MustCompile("^[0-1]{1,}$").MatchString
// BinaryToDecimal() function that will take Binary number as string,
// and return its Decimal equivalent as an integer.
func BinaryToDecimal(binary string) (int, error) {
if !isValid(binary) {
return -1, errors.New("not a valid binary string")
}
if len(binary) > 32 {
return -1, errors.New("binary number must be in range 0 to 2^(31-1)")
}
var result, base int = 0, 1
for i := len(binary) - 1; i >= 0; i-- {
if binary[i] == '1' {
result += base
}
base *= 2
}
return result, nil
}
View on GitHub (pinned to 5ba447ec5f)
Solutions
- Check len(binary) <= 32 before calling, and reject or chunk longer inputs.
- For larger values, use strconv.ParseUint(binary, 2, 64) instead of this library.
- Switch to math/big: new(big.Int).SetString(s, 2) for arbitrary precision.
Example fix
// before val, err := conversion.BinaryToDecimal(sixtyFourBits) // error: must be in range 0 to 2^(31-1) // after u, err := strconv.ParseUint(sixtyFourBits, 2, 64) // handles up to 64 bits
Defensive patterns
Strategy: validation
Validate before calling
func fitsIntBinary(s string) bool { return len(s) <= 32 } Try / catch
val, err := conversion.BinaryToDecimal(input)
if err != nil {
if err.Error() == "binary number must be in range 0 to 2^(31-1)" {
return fmt.Errorf("value too large for this converter: %w", err)
}
return err
} Prevention
- Check length <= 32 before converting.
- Use strconv.ParseUint(s, 2, 64) or math/big for wider values.
- Treat this converter as 31-bit-range only.
When it happens
Trigger: BinaryToDecimal called with a binary string longer than 32 characters, e.g. a 64-bit binary literal like "10000000000000000000000000000000001".
Common situations: Parsing 64-bit binary values (uint64 ranges) or binary hashes/MACs rendered as long bit strings; code assuming the function handles arbitrary-width binaries.
Related errors
- not a valid binary string
- integer must have +ve value
- input string is empty
- invalid hexadecimal string:
- invalid character in hexadecimal string:
AI-assisted analysis of TheAlgorithms/Go@5ba447ec5f (2026-09-02).
Data as JSON: /api/errors/9e97e4c5c326c374.
Report an issue: GitHub.