TheAlgorithms/Go · error

integer must have +ve value

Error message

integer must have +ve value

What it means

DecimalToBinary only supports non-negative integers because the repeated division-by-2 loop produces an infinite/negative loop for negative input. It returns this ad-hoc error when num < 0. num == 0 is handled specially and returns "0".

Source

Thrown at conversion/decimaltobinary.go:36

	"errors"
	"strconv"
)

// Reverse() function that will take string,
// and returns the reverse of that string.
func Reverse(str string) string {
	rStr := []rune(str)
	for i, j := 0, len(rStr)-1; i < len(rStr)/2; i, j = i+1, j-1 {
		rStr[i], rStr[j] = rStr[j], rStr[i]
	}
	return string(rStr)
}

// DecimalToBinary() function that will take Decimal number as int,
// and return its Binary equivalent as a string.
func DecimalToBinary(num int) (string, error) {
	if num < 0 {
		return "", errors.New("integer must have +ve value")
	}
	if num == 0 {
		return "0", nil
	}
	var result string = ""
	for num > 0 {
		result += strconv.Itoa(num & 1)
		num >>= 1
	}
	return Reverse(result), nil
}

View on GitHub (pinned to 5ba447ec5f)

Solutions

  1. Check num >= 0 before calling; reject or take math.Abs if magnitude is intended.
  2. For negative numbers, convert the magnitude and prefix '-' manually, or use strconv.FormatInt(int64(num), 2) which handles the sign.
  3. Fix upstream arithmetic that unexpectedly produces negative values.

Example fix

// before
b, err := conversion.DecimalToBinary(delta) // errors when delta < 0
// after
if delta >= 0 {
    b, err = conversion.DecimalToBinary(delta)
} else {
    b = "-" + strconv.FormatInt(int64(-delta), 2)
}
Defensive patterns

Strategy: validation

Validate before calling

func isNonNegative(n int) bool { return n >= 0 }

Try / catch

b, err := conversion.DecimalToBinary(num)
if err != nil {
    if err.Error() == "integer must have +ve value" {
        return fmt.Errorf("cannot convert negative number %d", num)
    }
    return err
}

Prevention

When it happens

Trigger: DecimalToBinary(-1) or any negative int, e.g. converting a signed value that went negative due to subtraction or a signed-byte cast.

Common situations: Converting temperature deltas, signed sensor readings, or results of integer underflow (e.g. 0 - 1 on unsigned-like logic) into binary.

Related errors


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