TheAlgorithms/Go · error

not a valid binary string

Error message

not a valid binary string

What it means

BinaryToDecimal validates its string input with the regex ^[0-1]{1,}$ and returns this ad-hoc error when the string contains characters other than 0 or 1 (or is empty). The library creates a fresh errors.New per call rather than an exported sentinel. It guards the bit-accumulation loop which assumes only '0' and '1'.

Source

Thrown at conversion/binarytodecimal.go:29

// Supported Binary number range is 0 to 2^(31-1).
// time complexity: O(n)
// space complexity: O(1)

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

  1. Validate with regexp ^[01]+$ (after TrimSpace) before calling BinaryToDecimal.
  2. Strip prefixes like "0b" and separators like "_" from user input first.
  3. Check err from BinaryToDecimal and map it to a user-facing 'enter only 0s and 1s' message.

Example fix

// before
val, err := conversion.BinaryToDecimal("0b1011") // error: not a valid binary string
// after
input := strings.TrimPrefix(strings.TrimSpace(raw), "0b")
if regexp.MustCompile(`^[01]+$`).MatchString(input) {
    val, err = conversion.BinaryToDecimal(input)
}
Defensive patterns

Strategy: validation

Validate before calling

var binaryRe = regexp.MustCompile(`^[01]+$`)
func isBinary(s string) bool { return binaryRe.MatchString(strings.TrimSpace(s)) }

Try / catch

val, err := conversion.BinaryToDecimal(input)
if err != nil {
    if err.Error() == "not a valid binary string" {
        return fmt.Errorf("%q is not binary (only 0/1 allowed)", input)
    }
    return err
}

Prevention

When it happens

Trigger: BinaryToDecimal("102"), BinaryToDecimal(""), BinaryToDecimal("0b101"), or any string with letters, spaces, sign characters, or separators.

Common situations: User-supplied input not sanitized (e.g. copy-pasted values with '0b' prefix, underscores, or whitespace), or locale-formatted numeric strings.

Related errors


AI-assisted analysis of TheAlgorithms/Go@5ba447ec5f (2026-09-02). Data as JSON: /api/errors/dd0bb6e4b437094d. Report an issue: GitHub.