Programming Search⌘K

Taskcore

Parse an integer

Also called convert a string to an integer, string to int, parse a number from a string, read an integer in a given base.

Parse a string as a signed 64-bit integer in a base from 2 to 36, with a strict syntax, and report bad text and a value out of range as two different errors.

Task

Parse a string as a signed 64-bit integer. The function takes the string and a base from 2 to 36. It returns the value, or it reports an error.

The syntax is strict. The string is one optional + or - and then one or more digits of the base. The digits are the ASCII characters 0 to 9 for the values 0 to 9, and the letters a to z or A to Z for the values 10 to 35. Each digit value is below the base. Leading zeros are allowed, and they do not change the base. Nothing else is allowed: no white space, no underscore, no thousands separator, no prefix such as 0x, no decimal point and no exponent.

The value is from -2^63 to 2^63 - 1. A solution reports two different errors, and a caller can tell them apart. An invalid string does not have the syntax above. An out-of-range string has the syntax, but its value is outside the range.

Text from a file, a command line, an environment variable or a network message comes in as a string. A strict parser rejects bad input at the edge of the program. A lax parser accepts "42px" as 42, or a value that does not fit as some other value.

Solutions

  • Python. int(s, base) also accepts white space, underscores, every Unicode decimal digit and a 0x prefix in base 16, and it has no upper limit. So the code checks each character against the digits of the base first. Then it calls int and checks the range. It raises ValueError for an invalid string and OverflowError for a value out of range.
  • JavaScript and TypeScript. Number.parseInt returns a double and stops at the first bad character (see Pitfalls). The code gets the value of each digit from its character code, adds it to a BigInt value, and returns a bigint. It throws SyntaxError or RangeError. The TypeScript file adds types only.
  • Java. Long.parseLong(s, radix) accepts a sign and rejects white space. It also accepts digits outside ASCII, because it uses Character.digit, and it throws NumberFormatException for both errors. So the code checks the syntax first, and it changes a later NumberFormatException into an ArithmeticException.
  • C#. In base 10, long.Parse with NumberStyles.AllowLeadingSign and the invariant culture matches the contract. It throws FormatException or OverflowException. Convert.ToInt64(s, base) takes only the bases 2, 8, 10 and 16, so the code has its own loop for the other bases. The loop uses checked arithmetic.
  • Go. strconv.ParseInt(s, base, 64) matches the contract. The error is a *strconv.NumError. errors.Is(err, strconv.ErrSyntax) and errors.Is(err, strconv.ErrRange) tell the two errors apart. Base 0 reads a prefix, so the code rejects it.
  • Rust. i64::from_str_radix(s, radix) matches the contract. err.kind() is Empty or InvalidDigit for an invalid string, and PosOverflow or NegOverflow for a value out of range. It panics when the radix is not from 2 to 36.
  • C. The code checks each character with its own digit table, because isalnum depends on the locale. Then it sets errno to 0 and calls strtoll. ERANGE in errno means the value is out of range. The function returns a status and writes the value through a pointer.
  • C++. std::from_chars takes no white space and no prefix, and it reports std::errc::result_out_of_range. It does not accept a + sign, so the code removes one. It then checks that from_chars read the whole string. The function returns std::expected<std::int64_t, std::errc>.
  • Bash. [[ $s =~ $re ]] checks the syntax with a bracket expression that lists each digit of the base. A loop adds one digit at a time and checks for overflow before each step. The function prints the value and returns 1 for an invalid string and 2 for a value out of range.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl. The inputs that must fail are in cases/errors.jsonl.

  • plus-sign and negative-zero: +5 is 5, and -0 is 0. An integer has no negative zero.
  • leading-zeros and many-leading-zeros: 007 is 7 in base 10, not an octal value. The string of 5,000 zeros and then 42 is valid. Python int rejects it because of its digit limit, so the Python code removes the leading zeros first.
  • max, min, max-hex and min-binary: the limits of the range. The minimum has no positive counterpart. So the C# loop adds each digit toward the sign of the result, and the Bash loop adds each digit toward the negative side.
  • upper-case and mixed-case: the letters of a digit can be in either case.
  • above-safe-integer: 2^53 + 1 has no exact double value. A parser that goes through a double gives 2^53.
  • trailing-newline: a line from a file or from standard input often ends in a newline. Remove it before you parse, and do not let the parser skip it.
  • hex-prefix, underscore and thousands-separator: the base is an argument, and the digits have no separators. Accept other syntax only on purpose, in a separate step.
  • arabic-indic-digits, fullwidth-digits and kelvin-sign: Python int and Java parseLong read the first two as 12. U+212A KELVIN SIGN is not the letter K, but Unicode case folding maps it to k. So a case-insensitive match with Unicode rules can accept it as a digit. The solutions accept only the ASCII letters.
  • hex-sign-bit and hex-all-ones: these are the bit patterns of -2^63 and -1. Their values are 2^63 and 2^64 - 1, so they are out of range. Convert.ToInt64 reads them as negative numbers.
  • min-times-ten and many-digits: a loop that stops at the limit must still report an error.
  • A string with too many digits and a bad character is in neither error class alone. Go and Rust stop at the first overflow and report a range error. The other solutions check the syntax first.

Pitfalls

  • Number.parseInt in JavaScript is lax. It skips leading white space, stops at the first bad character, reads 0x in base 16, and returns a double. Number("") is 0:

This code runs but gives a wrong answer on purpose.

console.log(Number.parseInt(" 42px", 10));
console.log(Number.parseInt("1e3", 10));
console.log(Number.parseInt("0x1A", 16));
console.log(Number.parseInt("9007199254740993", 10));
console.log(Number(""));
Output
42
1
26
9007199254740992
0
  • Python int accepts more than digits. It accepts white space, underscores, Unicode digits and a 0x prefix in base 16. Its result can be any size:

This code runs but gives a wrong answer on purpose.

print(int(" 42 "))
print(int("1_000"))
print(int("١٢"))
print(int("0x1A", 16))
print(int("9223372036854775808"))
Output
42
1000
12
26
9223372036854775808
  • Python limits the length of the string. A decimal string longer than 4,300 digits raises ValueError, even when its value is small. The limit protects against denial-of-service attacks:
s = "0" * 5000 + "42"
try:
    print(int(s))
except ValueError as e:
    print("ValueError:", e)
print(int(s.lstrip("0") or "0"))
Output
ValueError: Exceeds the limit (4300 digits) for integer string conversion: value has 5002 digits; use sys.set_int_max_str_digits() to increase the limit
42
  • Java parseLong has one exception for two errors. The exception for a bad character and the exception for a value out of range have the same type. parseLong also accepts Arabic-Indic digits:
public class Main {
  public static void main(String[] args) {
    System.out.println(Long.parseLong("١٢"));
    for (String s : new String[] {"12x", "9223372036854775808"}) {
      try {
        Long.parseLong(s);
      } catch (NumberFormatException e) {
        System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());
      }
    }
  }
}
Output
12
NumberFormatException: For input string: "12x"
NumberFormatException: For input string: "9223372036854775808"
  • C# Convert.ToInt64 with a base accepts 0x and wraps. In base 16 it reads a value above long.MaxValue as a negative number. long.Parse with the default style allows white space at both ends:

This code runs but gives a wrong answer on purpose.

using System.Globalization;

Console.WriteLine(Convert.ToInt64("0x1A", 16));
Console.WriteLine(Convert.ToInt64("ffffffffffffffff", 16));
Console.WriteLine(long.Parse(" 42 ", CultureInfo.InvariantCulture));
Output
26
-1
42
  • Go ParseInt returns a value with a range error. The value is the nearest limit, so check err before you use it. Base 0 reads a prefix, underscores and a leading 0 as octal:
package main

import (
	"fmt"
	"strconv"
)

func main() {
	fmt.Println(strconv.ParseInt("9223372036854775808", 10, 64))
	fmt.Println(strconv.ParseInt("017", 0, 64))
	fmt.Println(strconv.ParseInt("1_000", 0, 64))
}
Output
9223372036854775807 strconv.ParseInt: parsing "9223372036854775808": value out of range
15 <nil>
1000 <nil>
  • A line from input still has its newline. Rust parse does not skip white space, so a line that still ends in \n fails. Remove the line ending first:
fn main() {
    let line = "42\n";
    println!("{:?}", line.parse::<i64>());
    println!("{:?}", line.trim_end().parse::<i64>());
}
Output
Err(ParseIntError { kind: InvalidDigit })
Ok(42)
  • C strtoll reads a prefix of the string. It skips leading white space, stops at the first bad character, and reads 0x in base 16. Pass an end pointer and check that it is at the end of the string. On overflow it returns LLONG_MAX or LLONG_MIN and sets errno to ERANGE. It does not set errno to 0 on success, so set it to 0 before the call:

This code runs but gives a wrong answer on purpose.

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    const char *inputs[] = {" 42", "42px", "0x1A", "9223372036854775808"};
    const int bases[] = {10, 10, 16, 10};
    for (int i = 0; i < 4; i++) {
        char *end = NULL;
        errno = 0;
        long long value = strtoll(inputs[i], &end, bases[i]);
        printf("\"%s\": %lld, rest \"%s\", %s\n", inputs[i], value, end,
               errno == ERANGE ? "ERANGE" : "no error");
    }
    return 0;
}
Output
" 42": 42, rest "", no error
"42px": 42, rest "px", no error
"0x1A": 26, rest "", no error
"9223372036854775808": 9223372036854775807, rest "", ERANGE
  • C++ from_chars stops early and rejects +. It returns a pointer to the first character that it did not read. On a range error it does not change the value:
#include <charconv>
#include <cstdint>
#include <print>
#include <string_view>
#include <system_error>

int main() {
    for (std::string_view s : {"+5", "42px", "9223372036854775808"}) {
        std::int64_t value = -1;
        auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), value);
        const char *error = ec == std::errc{}                     ? "no error"
                            : ec == std::errc::invalid_argument ? "invalid_argument"
                                                                : "result_out_of_range";
        std::println("\"{}\": value {}, read {} of {} chars, {}", s, value, ptr - s.data(), s.size(),
                     error);
    }
}
Output
"+5": value -1, read 0 of 2 chars, invalid_argument
"42px": value 42, read 2 of 4 chars, no error
"9223372036854775808": value -1, read 19 of 19 chars, result_out_of_range
  • Bash arithmetic wraps and runs code. Shell arithmetic uses fixed-width integers and does not check for overflow (see Integer overflow or wraparound). A variable in an arithmetic expression is itself read as an expression, so a subscript with $(...) runs a command. Never put input text in $((...)) before you check it (see OS command injection):

This code runs but gives a wrong answer on purpose.

exec 2>&1
s=9223372036854775808
echo $((10#$s))
x='a[$(echo "this command ran" >&2)]'
echo $((x))
Output
-9223372036854775808
this command ran
0

Code

The build runs the native tests of each language in a pinned toolchain.

parse_integer.pyI0tests passRawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/parse-an-integer/.

_DIGITS = "0123456789abcdefghijklmnopqrstuvwxyz"
_MIN = -(2**63)
_MAX = 2**63 - 1


def parse_integer(s: str, base: int = 10) -> int:
    """Parse s as a signed 64-bit integer in the given base, from 2 to 36.

    Raise ValueError when s is not an optional sign and ASCII digits of the
    base, and OverflowError when the value does not fit in 64 bits.
    """
    allowed = _DIGITS[:base] + _DIGITS[10:base].upper()
    digits = s[1:] if s.startswith(("+", "-")) else s
    # int() alone also accepts white space, underscores, a 0x prefix and
    # every Unicode decimal digit, so check the characters first.
    if not digits or any(c not in allowed for c in digits):
        raise ValueError(f"invalid integer for base {base}: {s!r}")
    # A 64-bit value has at most 64 significant digits in any base. The
    # check also keeps a long string away from the digit limit of int().
    significant = digits.lstrip("0") or "0"
    if len(significant) > 64:
        raise OverflowError(f"integer out of range: {s!r}")
    value = int(significant, base)
    if s.startswith("-"):
        value = -value
    if not _MIN <= value <= _MAX:
        raise OverflowError(f"integer out of range: {s!r}")
    return value
test_parse_integer.py 78 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/parse-an-integer/.

import pytest

from parse_integer import parse_integer

CASES = {
    "decimal": ("42", 10, 42),
    "negative": ("-17", 10, -17),
    "hex": ("ff", 16, 255),
    "binary": ("101010", 2, 42),
    "base-36": ("zz", 36, 1295),
    "plus-sign": ("+5", 10, 5),
    "negative-zero": ("-0", 10, 0),
    "zero": ("0", 10, 0),
    "leading-zeros": ("007", 10, 7),
    "many-leading-zeros": ("0" * 5000 + "42", 10, 42),
    "max": ("9223372036854775807", 10, 9223372036854775807),
    "min": ("-9223372036854775808", 10, -9223372036854775808),
    "max-hex": ("7fffffffffffffff", 16, 9223372036854775807),
    "min-binary": ("-1" + "0" * 63, 2, -9223372036854775808),
    "upper-case": ("FF", 16, 255),
    "mixed-case": ("Zz", 36, 1295),
    "above-safe-integer": ("9007199254740993", 10, 9007199254740993),
}

INVALID = {
    "empty": ("", 10),
    "sign-only": ("-", 10),
    "plus-only": ("+", 10),
    "double-sign": ("+-5", 10),
    "leading-space": (" 42", 10),
    "trailing-space": ("42 ", 10),
    "trailing-newline": ("42\n", 10),
    "trailing-garbage": ("42px", 10),
    "underscore": ("1_000", 10),
    "thousands-separator": ("1,000", 10),
    "decimal-point": ("4.0", 10),
    "exponent": ("1e3", 10),
    "hex-prefix": ("0x1A", 16),
    "binary-prefix": ("0b101", 2),
    "digit-outside-base": ("102", 2),
    "letter-outside-base": ("fg", 16),
    "arabic-indic-digits": ("\u0661\u0662", 10),
    "fullwidth-digits": ("\uff11\uff12", 10),
    "kelvin-sign": ("\u212a", 36),
}

OUT_OF_RANGE = {
    "max-plus-one": ("9223372036854775808", 10),
    "min-minus-one": ("-9223372036854775809", 10),
    "two-to-the-64": ("18446744073709551616", 10),
    "hex-sign-bit": ("8000000000000000", 16),
    "hex-all-ones": ("ffffffffffffffff", 16),
    "min-times-ten": ("-92233720368547758080", 10),
    "many-digits": ("9" * 5000, 10),
}


@pytest.mark.parametrize("name", CASES)
def test_parse_integer(name):
    s, base, want = CASES[name]
    assert parse_integer(s, base) == want


@pytest.mark.parametrize("name", INVALID)
def test_invalid(name):
    s, base = INVALID[name]
    with pytest.raises(ValueError):
        parse_integer(s, base)


@pytest.mark.parametrize("name", OUT_OF_RANGE)
def test_out_of_range(name):
    s, base = OUT_OF_RANGE[name]
    with pytest.raises(OverflowError):
        parse_integer(s, base)
parse_integer.cppI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-an-integer/.

#include "parse_integer.hpp"

#include <charconv>

std::expected<std::int64_t, std::errc> parse_integer(std::string_view s, int base) {
    // std::from_chars accepts a minus sign but not a plus sign.
    if (s.size() >= 2 && s[0] == '+' && s[1] != '+' && s[1] != '-') {
        s.remove_prefix(1);
    }
    const char *end = s.data() + s.size();
    std::int64_t value = 0;
    auto [ptr, ec] = std::from_chars(s.data(), end, value, base);
    // from_chars stops at the first character that is not a digit, so check
    // that it read the whole string.
    if (ec == std::errc::invalid_argument || ptr != end) {
        return std::unexpected(std::errc::invalid_argument);
    }
    if (ec == std::errc::result_out_of_range) {
        return std::unexpected(ec);
    }
    return value;
}
parse_integer.hpp 15 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-an-integer/.

#pragma once

#include <cstdint>
#include <expected>
#include <string_view>
#include <system_error>

// parse_integer parses s as a signed 64-bit integer in the given base, from 2
// to 36. The error is std::errc::invalid_argument when s is not an optional
// sign and ASCII digits of the base, and std::errc::result_out_of_range when
// the value does not fit in std::int64_t.
std::expected<std::int64_t, std::errc> parse_integer(std::string_view s, int base);
test_parse_integer.cpp 103 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-an-integer/.

#include <cstdint>
#include <cstdio>
#include <limits>
#include <string>
#include <string_view>
#include <system_error>
#include <vector>

#include "parse_integer.hpp"

namespace {

int failures = 0;

void check(std::string_view name, bool ok) {
    if (!ok) {
        std::fprintf(stderr, "case %.*s failed\n", static_cast<int>(name.size()), name.data());
        ++failures;
    }
}

}  // namespace

int main() {
    struct Case {
        std::string_view name;
        std::string s;
        int base;
        std::int64_t want;
    };
    const std::vector<Case> cases = {
        {"decimal", "42", 10, 42},
        {"negative", "-17", 10, -17},
        {"hex", "ff", 16, 255},
        {"binary", "101010", 2, 42},
        {"base-36", "zz", 36, 1295},
        {"plus-sign", "+5", 10, 5},
        {"negative-zero", "-0", 10, 0},
        {"zero", "0", 10, 0},
        {"leading-zeros", "007", 10, 7},
        {"many-leading-zeros", std::string(5000, '0') + "42", 10, 42},
        {"max", "9223372036854775807", 10, 9223372036854775807LL},
        {"min", "-9223372036854775808", 10, std::numeric_limits<std::int64_t>::min()},
        {"max-hex", "7fffffffffffffff", 16, 9223372036854775807LL},
        {"min-binary", "-1000000000000000000000000000000000000000000000000000000000000000", 2, std::numeric_limits<std::int64_t>::min()},
        {"upper-case", "FF", 16, 255},
        {"mixed-case", "Zz", 36, 1295},
        {"above-safe-integer", "9007199254740993", 10, 9007199254740993LL},
    };
    for (const auto &c : cases) {
        auto got = parse_integer(c.s, c.base);
        check(c.name, got.has_value() && *got == c.want);
    }

    struct ErrorCase {
        std::string_view name;
        std::string s;
        int base;
        std::errc want;
    };
    const std::vector<ErrorCase> errors = {
        {"empty", "", 10, std::errc::invalid_argument},
        {"sign-only", "-", 10, std::errc::invalid_argument},
        {"plus-only", "+", 10, std::errc::invalid_argument},
        {"double-sign", "+-5", 10, std::errc::invalid_argument},
        {"leading-space", " 42", 10, std::errc::invalid_argument},
        {"trailing-space", "42 ", 10, std::errc::invalid_argument},
        {"trailing-newline", "42\n", 10, std::errc::invalid_argument},
        {"trailing-garbage", "42px", 10, std::errc::invalid_argument},
        {"underscore", "1_000", 10, std::errc::invalid_argument},
        {"thousands-separator", "1,000", 10, std::errc::invalid_argument},
        {"decimal-point", "4.0", 10, std::errc::invalid_argument},
        {"exponent", "1e3", 10, std::errc::invalid_argument},
        {"hex-prefix", "0x1A", 16, std::errc::invalid_argument},
        {"binary-prefix", "0b101", 2, std::errc::invalid_argument},
        {"digit-outside-base", "102", 2, std::errc::invalid_argument},
        {"letter-outside-base", "fg", 16, std::errc::invalid_argument},
        {"arabic-indic-digits", "\xd9\xa1\xd9\xa2", 10, std::errc::invalid_argument},
        {"fullwidth-digits", "\xef\xbc\x91\xef\xbc\x92", 10, std::errc::invalid_argument},
        {"kelvin-sign", "\xe2\x84\xaa", 36, std::errc::invalid_argument},
        {"max-plus-one", "9223372036854775808", 10, std::errc::result_out_of_range},
        {"min-minus-one", "-9223372036854775809", 10, std::errc::result_out_of_range},
        {"two-to-the-64", "18446744073709551616", 10, std::errc::result_out_of_range},
        {"hex-sign-bit", "8000000000000000", 16, std::errc::result_out_of_range},
        {"hex-all-ones", "ffffffffffffffff", 16, std::errc::result_out_of_range},
        {"min-times-ten", "-92233720368547758080", 10, std::errc::result_out_of_range},
        {"many-digits", std::string(5000, '9'), 10, std::errc::result_out_of_range},
    };
    for (const auto &c : errors) {
        auto got = parse_integer(c.s, c.base);
        check(c.name, !got.has_value() && got.error() == c.want);
    }

    if (failures > 0) {
        std::fprintf(stderr, "%d cases failed\n", failures);
        return 1;
    }
    std::printf("all cases passed\n");
    return 0;
}
ParseInteger.javaI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-an-integer/.

/** Parses a signed 64-bit integer with a strict syntax. */
public final class ParseInteger {
  private ParseInteger() {}

  /**
   * Parses s as a signed 64-bit integer in the given radix, from 2 to 36.
   *
   * @throws NumberFormatException if s is not an optional sign and ASCII digits of the radix
   * @throws ArithmeticException if the value does not fit in a long
   */
  public static long parseInteger(String s, int radix) {
    int start = s.startsWith("+") || s.startsWith("-") ? 1 : 0;
    if (start == s.length()) {
      throw invalid(s, radix);
    }
    for (int i = start; i < s.length(); i++) {
      char c = s.charAt(i);
      // Character.digit also accepts digits outside ASCII, such as U+0661.
      if (c > 0x7f || Character.digit(c, radix) < 0) {
        throw invalid(s, radix);
      }
    }
    try {
      return Long.parseLong(s, radix);
    } catch (NumberFormatException e) {
      // The syntax is valid, so the only cause left is a value out of range.
      throw new ArithmeticException("integer out of range: \"" + s + "\"");
    }
  }

  private static NumberFormatException invalid(String s, int radix) {
    return new NumberFormatException("invalid integer for radix " + radix + ": \"" + s + "\"");
  }
}
ParseIntegerTest.java 85 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-an-integer/.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class ParseIntegerTest {
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("decimal", "42", 10, 42),
        Arguments.of("negative", "-17", 10, -17),
        Arguments.of("hex", "ff", 16, 255),
        Arguments.of("binary", "101010", 2, 42),
        Arguments.of("base-36", "zz", 36, 1295),
        Arguments.of("plus-sign", "+5", 10, 5),
        Arguments.of("negative-zero", "-0", 10, 0),
        Arguments.of("zero", "0", 10, 0),
        Arguments.of("leading-zeros", "007", 10, 7),
        Arguments.of("many-leading-zeros", "0".repeat(5000) + "42", 10, 42),
        Arguments.of("max", "9223372036854775807", 10, 9223372036854775807L),
        Arguments.of("min", "-9223372036854775808", 10, Long.MIN_VALUE),
        Arguments.of("max-hex", "7fffffffffffffff", 16, 9223372036854775807L),
        Arguments.of("min-binary", "-1000000000000000000000000000000000000000000000000000000000000000", 2, Long.MIN_VALUE),
        Arguments.of("upper-case", "FF", 16, 255),
        Arguments.of("mixed-case", "Zz", 36, 1295),
        Arguments.of("above-safe-integer", "9007199254740993", 10, 9007199254740993L));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void parses(String name, String s, int radix, long want) {
    assertEquals(want, ParseInteger.parseInteger(s, radix));
  }

  static Stream<Arguments> invalid() {
    return Stream.of(
        Arguments.of("empty", "", 10),
        Arguments.of("sign-only", "-", 10),
        Arguments.of("plus-only", "+", 10),
        Arguments.of("double-sign", "+-5", 10),
        Arguments.of("leading-space", " 42", 10),
        Arguments.of("trailing-space", "42 ", 10),
        Arguments.of("trailing-newline", "42\n", 10),
        Arguments.of("trailing-garbage", "42px", 10),
        Arguments.of("underscore", "1_000", 10),
        Arguments.of("thousands-separator", "1,000", 10),
        Arguments.of("decimal-point", "4.0", 10),
        Arguments.of("exponent", "1e3", 10),
        Arguments.of("hex-prefix", "0x1A", 16),
        Arguments.of("binary-prefix", "0b101", 2),
        Arguments.of("digit-outside-base", "102", 2),
        Arguments.of("letter-outside-base", "fg", 16),
        Arguments.of("arabic-indic-digits", "\u0661\u0662", 10),
        Arguments.of("fullwidth-digits", "\uff11\uff12", 10),
        Arguments.of("kelvin-sign", "\u212a", 36));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("invalid")
  void rejectsInvalid(String name, String s, int radix) {
    assertThrows(NumberFormatException.class, () -> ParseInteger.parseInteger(s, radix));
  }

  static Stream<Arguments> outOfRange() {
    return Stream.of(
        Arguments.of("max-plus-one", "9223372036854775808", 10),
        Arguments.of("min-minus-one", "-9223372036854775809", 10),
        Arguments.of("two-to-the-64", "18446744073709551616", 10),
        Arguments.of("hex-sign-bit", "8000000000000000", 16),
        Arguments.of("hex-all-ones", "ffffffffffffffff", 16),
        Arguments.of("min-times-ten", "-92233720368547758080", 10),
        Arguments.of("many-digits", "9".repeat(5000), 10));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("outOfRange")
  void rejectsOutOfRange(String name, String s, int radix) {
    assertThrows(ArithmeticException.class, () -> ParseInteger.parseInteger(s, radix));
  }
}
parse_integer.cI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-an-integer/.

#include "parse_integer.h"

#include <errno.h>
#include <stdlib.h>

// digit_value returns the value of one ASCII digit or letter, or -1. It does
// not use isalnum or tolower, because their result depends on the locale.
static int digit_value(char c) {
    static const char lower[] = "0123456789abcdefghijklmnopqrstuvwxyz";
    static const char upper[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    for (int i = 0; i < 36; i++) {
        if (c == lower[i] || c == upper[i]) {
            return i;
        }
    }
    return -1;
}

enum parse_status parse_integer(const char *s, int base, int64_t *out) {
    // strtoll skips white space, reads a 0x prefix in base 16 and stops at
    // the first bad character, so check the whole string first.
    const char *p = s;
    if (*p == '+' || *p == '-') {
        p++;
    }
    if (*p == '\0') {
        return PARSE_INVALID;
    }
    for (; *p != '\0'; p++) {
        int d = digit_value(*p);
        if (d < 0 || d >= base) {
            return PARSE_INVALID;
        }
    }
    // strtoll sets errno only on an error, so clear it first.
    errno = 0;
    long long value = strtoll(s, NULL, base);
    if (errno == ERANGE) {
        return PARSE_RANGE;
    }
    *out = value;
    return PARSE_OK;
}
parse_integer.h 19 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-an-integer/.

#ifndef PARSE_INTEGER_H
#define PARSE_INTEGER_H

#include <stdint.h>

enum parse_status {
    PARSE_OK,      // *out holds the value
    PARSE_INVALID, // s is not an optional sign and ASCII digits of the base
    PARSE_RANGE,   // the value does not fit in int64_t
};

// parse_integer parses the string s as a signed 64-bit integer in the given
// base, from 2 to 36. It writes *out only when it returns PARSE_OK.
enum parse_status parse_integer(const char *s, int base, int64_t *out);

#endif
test_parse_integer.c 100 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-an-integer/.

#include "parse_integer.h"

#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static int failures = 0;

static void ok(const char *name, const char *s, int base, int64_t want) {
    int64_t got = 0;
    enum parse_status status = parse_integer(s, base, &got);
    if (status != PARSE_OK || got != want) {
        fprintf(stderr, "case %s failed: status %d, got %" PRId64 "\n", name, (int)status, got);
        failures++;
    }
}

static void fails(const char *name, const char *s, int base, enum parse_status want) {
    int64_t got = 0;
    enum parse_status status = parse_integer(s, base, &got);
    if (status != want) {
        fprintf(stderr, "case %s failed: status %d, want %d\n", name, (int)status, (int)want);
        failures++;
    }
}

// repeat returns n copies of c followed by tail, in memory from malloc.
static char *repeat(char c, size_t n, const char *tail) {
    size_t len = strlen(tail);
    char *s = malloc(n + len + 1);
    if (s == NULL) {
        exit(1);
    }
    memset(s, c, n);
    memcpy(s + n, tail, len + 1);
    return s;
}

int main(void) {
    char *zeros = repeat('0', 5000, "42");
    char *nines = repeat('9', 5000, "");

    ok("decimal", "42", 10, INT64_C(42));
    ok("negative", "-17", 10, INT64_C(-17));
    ok("hex", "ff", 16, INT64_C(255));
    ok("binary", "101010", 2, INT64_C(42));
    ok("base-36", "zz", 36, INT64_C(1295));
    ok("plus-sign", "+5", 10, INT64_C(5));
    ok("negative-zero", "-0", 10, INT64_C(0));
    ok("zero", "0", 10, INT64_C(0));
    ok("leading-zeros", "007", 10, INT64_C(7));
    ok("many-leading-zeros", zeros, 10, INT64_C(42));
    ok("max", "9223372036854775807", 10, INT64_C(9223372036854775807));
    ok("min", "-9223372036854775808", 10, INT64_MIN);
    ok("max-hex", "7fffffffffffffff", 16, INT64_C(9223372036854775807));
    ok("min-binary", "-1000000000000000000000000000000000000000000000000000000000000000", 2, INT64_MIN);
    ok("upper-case", "FF", 16, INT64_C(255));
    ok("mixed-case", "Zz", 36, INT64_C(1295));
    ok("above-safe-integer", "9007199254740993", 10, INT64_C(9007199254740993));

    fails("empty", "", 10, PARSE_INVALID);
    fails("sign-only", "-", 10, PARSE_INVALID);
    fails("plus-only", "+", 10, PARSE_INVALID);
    fails("double-sign", "+-5", 10, PARSE_INVALID);
    fails("leading-space", " 42", 10, PARSE_INVALID);
    fails("trailing-space", "42 ", 10, PARSE_INVALID);
    fails("trailing-newline", "42\n", 10, PARSE_INVALID);
    fails("trailing-garbage", "42px", 10, PARSE_INVALID);
    fails("underscore", "1_000", 10, PARSE_INVALID);
    fails("thousands-separator", "1,000", 10, PARSE_INVALID);
    fails("decimal-point", "4.0", 10, PARSE_INVALID);
    fails("exponent", "1e3", 10, PARSE_INVALID);
    fails("hex-prefix", "0x1A", 16, PARSE_INVALID);
    fails("binary-prefix", "0b101", 2, PARSE_INVALID);
    fails("digit-outside-base", "102", 2, PARSE_INVALID);
    fails("letter-outside-base", "fg", 16, PARSE_INVALID);
    fails("arabic-indic-digits", "\xd9\xa1\xd9\xa2", 10, PARSE_INVALID);
    fails("fullwidth-digits", "\xef\xbc\x91\xef\xbc\x92", 10, PARSE_INVALID);
    fails("kelvin-sign", "\xe2\x84\xaa", 36, PARSE_INVALID);
    fails("max-plus-one", "9223372036854775808", 10, PARSE_RANGE);
    fails("min-minus-one", "-9223372036854775809", 10, PARSE_RANGE);
    fails("two-to-the-64", "18446744073709551616", 10, PARSE_RANGE);
    fails("hex-sign-bit", "8000000000000000", 16, PARSE_RANGE);
    fails("hex-all-ones", "ffffffffffffffff", 16, PARSE_RANGE);
    fails("min-times-ten", "-92233720368547758080", 10, PARSE_RANGE);
    fails("many-digits", nines, 10, PARSE_RANGE);

    free(zeros);
    free(nines);
    if (failures > 0) {
        fprintf(stderr, "%d cases failed\n", failures);
        return 1;
    }
    printf("all cases passed\n");
    return 0;
}
ParseInteger.csI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-an-integer/.

using System;
using System.Globalization;

/// <summary>Parses a signed 64-bit integer with a strict syntax.</summary>
public static class IntegerParser
{
    /// <summary>
    /// Parses s as a signed 64-bit integer in the given radix, from 2 to 36. Throws a
    /// FormatException when s is not an optional sign and ASCII digits of the radix, and an
    /// OverflowException when the value does not fit in a long.
    /// </summary>
    public static long ParseInteger(string s, int radix)
    {
        if (radix == 10)
        {
            // AllowLeadingSign alone turns off the white space that the default style allows.
            return long.Parse(s, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture);
        }
        // Convert.ToInt64 takes only the bases 2, 8, 10 and 16, accepts a 0x prefix and
        // reads a hex value above long.MaxValue as negative, so check the digits here.
        bool negative = s.StartsWith('-');
        int start = negative || s.StartsWith('+') ? 1 : 0;
        if (start == s.Length)
        {
            throw Invalid(s, radix);
        }
        foreach (char c in s.AsSpan(start))
        {
            int d = DigitValue(c);
            if (d < 0 || d >= radix)
            {
                throw Invalid(s, radix);
            }
        }
        long value = 0;
        foreach (char c in s.AsSpan(start))
        {
            // Add toward the sign, so long.MinValue fits. checked throws OverflowException.
            int d = DigitValue(c);
            value = checked(value * radix + (negative ? -d : d));
        }
        return value;
    }

    private static int DigitValue(char c) => c switch
    {
        >= '0' and <= '9' => c - '0',
        >= 'a' and <= 'z' => c - 'a' + 10,
        >= 'A' and <= 'Z' => c - 'A' + 10,
        _ => -1,
    };

    private static FormatException Invalid(string s, int radix) =>
        new($"invalid integer for radix {radix}: \"{s}\"");
}
ParseIntegerTests.cs 87 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-an-integer/.

using System;
using Xunit;

public sealed class ParseIntegerTests
{
    public static TheoryData<string, string, int, long> Cases => new()
    {
        { "decimal", "42", 10, 42 },
        { "negative", "-17", 10, -17 },
        { "hex", "ff", 16, 255 },
        { "binary", "101010", 2, 42 },
        { "base-36", "zz", 36, 1295 },
        { "plus-sign", "+5", 10, 5 },
        { "negative-zero", "-0", 10, 0 },
        { "zero", "0", 10, 0 },
        { "leading-zeros", "007", 10, 7 },
        { "many-leading-zeros", new string('0', 5000) + "42", 10, 42 },
        { "max", "9223372036854775807", 10, 9223372036854775807 },
        { "min", "-9223372036854775808", 10, long.MinValue },
        { "max-hex", "7fffffffffffffff", 16, 9223372036854775807 },
        { "min-binary", "-1000000000000000000000000000000000000000000000000000000000000000", 2, long.MinValue },
        { "upper-case", "FF", 16, 255 },
        { "mixed-case", "Zz", 36, 1295 },
        { "above-safe-integer", "9007199254740993", 10, 9007199254740993 },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Parses(string name, string s, int radix, long want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, IntegerParser.ParseInteger(s, radix));
    }

    public static TheoryData<string, string, int> Invalid => new()
    {
        { "empty", "", 10 },
        { "sign-only", "-", 10 },
        { "plus-only", "+", 10 },
        { "double-sign", "+-5", 10 },
        { "leading-space", " 42", 10 },
        { "trailing-space", "42 ", 10 },
        { "trailing-newline", "42\n", 10 },
        { "trailing-garbage", "42px", 10 },
        { "underscore", "1_000", 10 },
        { "thousands-separator", "1,000", 10 },
        { "decimal-point", "4.0", 10 },
        { "exponent", "1e3", 10 },
        { "hex-prefix", "0x1A", 16 },
        { "binary-prefix", "0b101", 2 },
        { "digit-outside-base", "102", 2 },
        { "letter-outside-base", "fg", 16 },
        { "arabic-indic-digits", "\u0661\u0662", 10 },
        { "fullwidth-digits", "\uff11\uff12", 10 },
        { "kelvin-sign", "\u212a", 36 },
    };

    [Theory]
    [MemberData(nameof(Invalid))]
    public void RejectsInvalid(string name, string s, int radix)
    {
        Assert.NotNull(name);
        Assert.Throws<FormatException>(() => IntegerParser.ParseInteger(s, radix));
    }

    public static TheoryData<string, string, int> OutOfRange => new()
    {
        { "max-plus-one", "9223372036854775808", 10 },
        { "min-minus-one", "-9223372036854775809", 10 },
        { "two-to-the-64", "18446744073709551616", 10 },
        { "hex-sign-bit", "8000000000000000", 16 },
        { "hex-all-ones", "ffffffffffffffff", 16 },
        { "min-times-ten", "-92233720368547758080", 10 },
        { "many-digits", new string('9', 5000), 10 },
    };

    [Theory]
    [MemberData(nameof(OutOfRange))]
    public void RejectsOutOfRange(string name, string s, int radix)
    {
        Assert.NotNull(name);
        Assert.Throws<OverflowException>(() => IntegerParser.ParseInteger(s, radix));
    }
}
parseInteger.jsI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-an-integer/.

const MIN = -(2n ** 63n);
const MAX = 2n ** 63n - 1n;
const LIMIT = 2n ** 63n;

// digitValue returns the value of one ASCII digit or letter, or -1. It does
// not use a regular expression with the i and u flags, because that matches
// the Kelvin sign U+212A as the letter k.
function digitValue(c) {
  const code = c.charCodeAt(0);
  if (code >= 48 && code <= 57) return code - 48; // 0 to 9
  if (code >= 97 && code <= 122) return code - 87; // a to z
  if (code >= 65 && code <= 90) return code - 55; // A to Z
  return -1;
}

/**
 * Parses s as a signed 64-bit integer in the given base, from 2 to 36, and
 * returns a bigint. Throws a SyntaxError when s is not an optional sign and
 * ASCII digits of the base, and a RangeError when the value does not fit.
 */
export function parseInteger(s, base = 10) {
  const negative = s.startsWith("-");
  const digits = negative || s.startsWith("+") ? s.slice(1) : s;
  if (digits === "") {
    throw new SyntaxError(`invalid integer for base ${base}: ${JSON.stringify(s)}`);
  }
  const radix = BigInt(base);
  let value = 0n;
  for (const c of digits) {
    const d = digitValue(c);
    if (d < 0 || d >= base) {
      throw new SyntaxError(`invalid integer for base ${base}: ${JSON.stringify(s)}`);
    }
    // Stop once the value is above 2^63, so a long string of digits does
    // not build a huge bigint. The value stays above the range.
    if (value <= LIMIT) value = value * radix + BigInt(d);
  }
  if (negative) value = -value;
  if (value < MIN || value > MAX) {
    throw new RangeError(`integer out of range: ${JSON.stringify(s)}`);
  }
  return value;
}
parseInteger.test.js 77 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-an-integer/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { parseInteger } from "./parseInteger.js";

const cases = [
  ["decimal", "42", 10, 42n],
  ["negative", "-17", 10, -17n],
  ["hex", "ff", 16, 255n],
  ["binary", "101010", 2, 42n],
  ["base-36", "zz", 36, 1295n],
  ["plus-sign", "+5", 10, 5n],
  ["negative-zero", "-0", 10, 0n],
  ["zero", "0", 10, 0n],
  ["leading-zeros", "007", 10, 7n],
  ["many-leading-zeros", "0".repeat(5000) + "42", 10, 42n],
  ["max", "9223372036854775807", 10, 9223372036854775807n],
  ["min", "-9223372036854775808", 10, -9223372036854775808n],
  ["max-hex", "7fffffffffffffff", 16, 9223372036854775807n],
  ["min-binary", "-1" + "0".repeat(63), 2, -9223372036854775808n],
  ["upper-case", "FF", 16, 255n],
  ["mixed-case", "Zz", 36, 1295n],
  ["above-safe-integer", "9007199254740993", 10, 9007199254740993n],
];

const invalid = [
  ["empty", "", 10],
  ["sign-only", "-", 10],
  ["plus-only", "+", 10],
  ["double-sign", "+-5", 10],
  ["leading-space", " 42", 10],
  ["trailing-space", "42 ", 10],
  ["trailing-newline", "42\n", 10],
  ["trailing-garbage", "42px", 10],
  ["underscore", "1_000", 10],
  ["thousands-separator", "1,000", 10],
  ["decimal-point", "4.0", 10],
  ["exponent", "1e3", 10],
  ["hex-prefix", "0x1A", 16],
  ["binary-prefix", "0b101", 2],
  ["digit-outside-base", "102", 2],
  ["letter-outside-base", "fg", 16],
  ["arabic-indic-digits", "\u0661\u0662", 10],
  ["fullwidth-digits", "\uff11\uff12", 10],
  ["kelvin-sign", "\u212a", 36],
];

const outOfRange = [
  ["max-plus-one", "9223372036854775808", 10],
  ["min-minus-one", "-9223372036854775809", 10],
  ["two-to-the-64", "18446744073709551616", 10],
  ["hex-sign-bit", "8000000000000000", 16],
  ["hex-all-ones", "ffffffffffffffff", 16],
  ["min-times-ten", "-92233720368547758080", 10],
  ["many-digits", "9".repeat(5000), 10],
];

for (const [name, s, base, want] of cases) {
  test(name, () => {
    assert.equal(parseInteger(s, base), want);
  });
}

for (const [name, s, base] of invalid) {
  test(name, () => {
    assert.throws(() => parseInteger(s, base), SyntaxError);
  });
}

for (const [name, s, base] of outOfRange) {
  test(name, () => {
    assert.throws(() => parseInteger(s, base), RangeError);
  });
}
parseInteger.tsI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-an-integer/.

const MIN = -(2n ** 63n);
const MAX = 2n ** 63n - 1n;
const LIMIT = 2n ** 63n;

// digitValue returns the value of one ASCII digit or letter, or -1. It does
// not use a regular expression with the i and u flags, because that matches
// the Kelvin sign U+212A as the letter k.
function digitValue(c: string): number {
  const code = c.charCodeAt(0);
  if (code >= 48 && code <= 57) return code - 48; // 0 to 9
  if (code >= 97 && code <= 122) return code - 87; // a to z
  if (code >= 65 && code <= 90) return code - 55; // A to Z
  return -1;
}

/**
 * Parses s as a signed 64-bit integer in the given base, from 2 to 36, and
 * returns a bigint. Throws a SyntaxError when s is not an optional sign and
 * ASCII digits of the base, and a RangeError when the value does not fit.
 */
export function parseInteger(s: string, base = 10): bigint {
  const negative = s.startsWith("-");
  const digits = negative || s.startsWith("+") ? s.slice(1) : s;
  if (digits === "") {
    throw new SyntaxError(`invalid integer for base ${base}: ${JSON.stringify(s)}`);
  }
  const radix = BigInt(base);
  let value = 0n;
  for (const c of digits) {
    const d = digitValue(c);
    if (d < 0 || d >= base) {
      throw new SyntaxError(`invalid integer for base ${base}: ${JSON.stringify(s)}`);
    }
    // Stop once the value is above 2^63, so a long string of digits does
    // not build a huge bigint. The value stays above the range.
    if (value <= LIMIT) value = value * radix + BigInt(d);
  }
  if (negative) value = -value;
  if (value < MIN || value > MAX) {
    throw new RangeError(`integer out of range: ${JSON.stringify(s)}`);
  }
  return value;
}
parseInteger.test.ts 77 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-an-integer/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { parseInteger } from "./parseInteger.ts";

const cases: [string, string, number, bigint][] = [
  ["decimal", "42", 10, 42n],
  ["negative", "-17", 10, -17n],
  ["hex", "ff", 16, 255n],
  ["binary", "101010", 2, 42n],
  ["base-36", "zz", 36, 1295n],
  ["plus-sign", "+5", 10, 5n],
  ["negative-zero", "-0", 10, 0n],
  ["zero", "0", 10, 0n],
  ["leading-zeros", "007", 10, 7n],
  ["many-leading-zeros", "0".repeat(5000) + "42", 10, 42n],
  ["max", "9223372036854775807", 10, 9223372036854775807n],
  ["min", "-9223372036854775808", 10, -9223372036854775808n],
  ["max-hex", "7fffffffffffffff", 16, 9223372036854775807n],
  ["min-binary", "-1" + "0".repeat(63), 2, -9223372036854775808n],
  ["upper-case", "FF", 16, 255n],
  ["mixed-case", "Zz", 36, 1295n],
  ["above-safe-integer", "9007199254740993", 10, 9007199254740993n],
];

const invalid: [string, string, number][] = [
  ["empty", "", 10],
  ["sign-only", "-", 10],
  ["plus-only", "+", 10],
  ["double-sign", "+-5", 10],
  ["leading-space", " 42", 10],
  ["trailing-space", "42 ", 10],
  ["trailing-newline", "42\n", 10],
  ["trailing-garbage", "42px", 10],
  ["underscore", "1_000", 10],
  ["thousands-separator", "1,000", 10],
  ["decimal-point", "4.0", 10],
  ["exponent", "1e3", 10],
  ["hex-prefix", "0x1A", 16],
  ["binary-prefix", "0b101", 2],
  ["digit-outside-base", "102", 2],
  ["letter-outside-base", "fg", 16],
  ["arabic-indic-digits", "\u0661\u0662", 10],
  ["fullwidth-digits", "\uff11\uff12", 10],
  ["kelvin-sign", "\u212a", 36],
];

const outOfRange: [string, string, number][] = [
  ["max-plus-one", "9223372036854775808", 10],
  ["min-minus-one", "-9223372036854775809", 10],
  ["two-to-the-64", "18446744073709551616", 10],
  ["hex-sign-bit", "8000000000000000", 16],
  ["hex-all-ones", "ffffffffffffffff", 16],
  ["min-times-ten", "-92233720368547758080", 10],
  ["many-digits", "9".repeat(5000), 10],
];

for (const [name, s, base, want] of cases) {
  test(name, () => {
    assert.equal(parseInteger(s, base), want);
  });
}

for (const [name, s, base] of invalid) {
  test(name, () => {
    assert.throws(() => parseInteger(s, base), SyntaxError);
  });
}

for (const [name, s, base] of outOfRange) {
  test(name, () => {
    assert.throws(() => parseInteger(s, base), RangeError);
  });
}
parse_integer.goI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-an-integer/.

// Package parseinteger parses a signed 64-bit integer with a strict syntax.
package parseinteger

import "strconv"

// ParseInteger parses s as a signed 64-bit integer in the given base, from 2
// to 36. The error is a *strconv.NumError that wraps strconv.ErrSyntax when s
// is not an optional sign and ASCII digits of the base, and strconv.ErrRange
// when the value does not fit in an int64.
func ParseInteger(s string, base int) (int64, error) {
	if base == 0 {
		// Base 0 reads a prefix such as 0x and allows underscores.
		return 0, &strconv.NumError{Func: "ParseInteger", Num: s, Err: strconv.ErrSyntax}
	}
	return strconv.ParseInt(s, base, 64)
}
parse_integer_test.go 89 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-an-integer/.

package parseinteger

import (
	"errors"
	"math"
	"strconv"
	"strings"
	"testing"
)

func TestParseInteger(t *testing.T) {
	cases := []struct {
		name, s string
		base    int
		want    int64
	}{
		{"decimal", "42", 10, 42},
		{"negative", "-17", 10, -17},
		{"hex", "ff", 16, 255},
		{"binary", "101010", 2, 42},
		{"base-36", "zz", 36, 1295},
		{"plus-sign", "+5", 10, 5},
		{"negative-zero", "-0", 10, 0},
		{"zero", "0", 10, 0},
		{"leading-zeros", "007", 10, 7},
		{"many-leading-zeros", strings.Repeat("0", 5000) + "42", 10, 42},
		{"max", "9223372036854775807", 10, 9223372036854775807},
		{"min", "-9223372036854775808", 10, math.MinInt64},
		{"max-hex", "7fffffffffffffff", 16, 9223372036854775807},
		{"min-binary", "-1000000000000000000000000000000000000000000000000000000000000000", 2, math.MinInt64},
		{"upper-case", "FF", 16, 255},
		{"mixed-case", "Zz", 36, 1295},
		{"above-safe-integer", "9007199254740993", 10, 9007199254740993},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			got, err := ParseInteger(c.s, c.base)
			if err != nil || got != c.want {
				t.Errorf("got %d, %v; want %d", got, err, c.want)
			}
		})
	}
}

func TestParseIntegerErrors(t *testing.T) {
	cases := []struct {
		name, s string
		base    int
		want    error
	}{
		{"empty", "", 10, strconv.ErrSyntax},
		{"sign-only", "-", 10, strconv.ErrSyntax},
		{"plus-only", "+", 10, strconv.ErrSyntax},
		{"double-sign", "+-5", 10, strconv.ErrSyntax},
		{"leading-space", " 42", 10, strconv.ErrSyntax},
		{"trailing-space", "42 ", 10, strconv.ErrSyntax},
		{"trailing-newline", "42\n", 10, strconv.ErrSyntax},
		{"trailing-garbage", "42px", 10, strconv.ErrSyntax},
		{"underscore", "1_000", 10, strconv.ErrSyntax},
		{"thousands-separator", "1,000", 10, strconv.ErrSyntax},
		{"decimal-point", "4.0", 10, strconv.ErrSyntax},
		{"exponent", "1e3", 10, strconv.ErrSyntax},
		{"hex-prefix", "0x1A", 16, strconv.ErrSyntax},
		{"binary-prefix", "0b101", 2, strconv.ErrSyntax},
		{"digit-outside-base", "102", 2, strconv.ErrSyntax},
		{"letter-outside-base", "fg", 16, strconv.ErrSyntax},
		{"arabic-indic-digits", "\u0661\u0662", 10, strconv.ErrSyntax},
		{"fullwidth-digits", "\uff11\uff12", 10, strconv.ErrSyntax},
		{"kelvin-sign", "\u212a", 36, strconv.ErrSyntax},
		{"max-plus-one", "9223372036854775808", 10, strconv.ErrRange},
		{"min-minus-one", "-9223372036854775809", 10, strconv.ErrRange},
		{"two-to-the-64", "18446744073709551616", 10, strconv.ErrRange},
		{"hex-sign-bit", "8000000000000000", 16, strconv.ErrRange},
		{"hex-all-ones", "ffffffffffffffff", 16, strconv.ErrRange},
		{"min-times-ten", "-92233720368547758080", 10, strconv.ErrRange},
		{"many-digits", strings.Repeat("9", 5000), 10, strconv.ErrRange},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			_, err := ParseInteger(c.s, c.base)
			if !errors.Is(err, c.want) {
				t.Errorf("got error %v; want %v", err, c.want)
			}
		})
	}
}
parse_integer.rsI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-an-integer/.

use std::num::ParseIntError;

/// Parses `s` as a signed 64-bit integer in the given radix, from 2 to 36.
///
/// The error kind is `Empty` or `InvalidDigit` when `s` is not an optional
/// sign and ASCII digits of the radix, and `PosOverflow` or `NegOverflow`
/// when the value does not fit in an `i64`.
///
/// # Panics
///
/// Panics when `radix` is not in the range from 2 to 36.
pub fn parse_integer(s: &str, radix: u32) -> Result<i64, ParseIntError> {
    i64::from_str_radix(s, radix)
}
tests/parse_integer_test.rs 84 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-an-integer/.

use std::num::IntErrorKind;

use algo_parse_an_integer::parse_integer;

#[test]
fn parses() {
    let cases: Vec<(&str, String, u32, i64)> = vec![
        ("decimal", "42".to_string(), 10, 42),
        ("negative", "-17".to_string(), 10, -17),
        ("hex", "ff".to_string(), 16, 255),
        ("binary", "101010".to_string(), 2, 42),
        ("base-36", "zz".to_string(), 36, 1295),
        ("plus-sign", "+5".to_string(), 10, 5),
        ("negative-zero", "-0".to_string(), 10, 0),
        ("zero", "0".to_string(), 10, 0),
        ("leading-zeros", "007".to_string(), 10, 7),
        ("many-leading-zeros", "0".repeat(5000) + "42", 10, 42),
        ("max", "9223372036854775807".to_string(), 10, 9223372036854775807),
        ("min", "-9223372036854775808".to_string(), 10, i64::MIN),
        ("max-hex", "7fffffffffffffff".to_string(), 16, 9223372036854775807),
        ("min-binary", "-1000000000000000000000000000000000000000000000000000000000000000".to_string(), 2, i64::MIN),
        ("upper-case", "FF".to_string(), 16, 255),
        ("mixed-case", "Zz".to_string(), 36, 1295),
        ("above-safe-integer", "9007199254740993".to_string(), 10, 9007199254740993),
    ];
    for (name, s, radix, want) in cases {
        assert_eq!(parse_integer(&s, radix), Ok(want), "case {name}");
    }
}

#[test]
fn rejects_invalid() {
    let cases: Vec<(&str, String, u32)> = vec![
        ("empty", "".to_string(), 10),
        ("sign-only", "-".to_string(), 10),
        ("plus-only", "+".to_string(), 10),
        ("double-sign", "+-5".to_string(), 10),
        ("leading-space", " 42".to_string(), 10),
        ("trailing-space", "42 ".to_string(), 10),
        ("trailing-newline", "42\n".to_string(), 10),
        ("trailing-garbage", "42px".to_string(), 10),
        ("underscore", "1_000".to_string(), 10),
        ("thousands-separator", "1,000".to_string(), 10),
        ("decimal-point", "4.0".to_string(), 10),
        ("exponent", "1e3".to_string(), 10),
        ("hex-prefix", "0x1A".to_string(), 16),
        ("binary-prefix", "0b101".to_string(), 2),
        ("digit-outside-base", "102".to_string(), 2),
        ("letter-outside-base", "fg".to_string(), 16),
        ("arabic-indic-digits", "\u{661}\u{662}".to_string(), 10),
        ("fullwidth-digits", "\u{ff11}\u{ff12}".to_string(), 10),
        ("kelvin-sign", "\u{212a}".to_string(), 36),
    ];
    for (name, s, radix) in cases {
        let kind = parse_integer(&s, radix).map_err(|e| e.kind().clone());
        assert!(
            matches!(kind, Err(IntErrorKind::Empty | IntErrorKind::InvalidDigit)),
            "case {name}: {kind:?}"
        );
    }
}

#[test]
fn rejects_out_of_range() {
    let cases: Vec<(&str, String, u32)> = vec![
        ("max-plus-one", "9223372036854775808".to_string(), 10),
        ("min-minus-one", "-9223372036854775809".to_string(), 10),
        ("two-to-the-64", "18446744073709551616".to_string(), 10),
        ("hex-sign-bit", "8000000000000000".to_string(), 16),
        ("hex-all-ones", "ffffffffffffffff".to_string(), 16),
        ("min-times-ten", "-92233720368547758080".to_string(), 10),
        ("many-digits", "9".repeat(5000), 10),
    ];
    for (name, s, radix) in cases {
        let kind = parse_integer(&s, radix).map_err(|e| e.kind().clone());
        assert!(
            matches!(kind, Err(IntErrorKind::PosOverflow | IntErrorKind::NegOverflow)),
            "case {name}: {kind:?}"
        );
    }
}
parse_integer.shI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/parse-an-integer/.

# parse_integer S [BASE]: prints the value of S as a signed 64-bit integer in
# BASE, from 2 to 36 (10 by default). Returns 1 when S is not an optional sign
# and ASCII digits of the base, and 2 when the value does not fit in 64 bits.
parse_integer() {
  local s=$1 base=${2:-10}
  local lower=0123456789abcdefghijklmnopqrstuvwxyz
  local upper=0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ
  # List the digits one by one. Outside the POSIX locale, the meaning of a
  # range such as a-z is not specified.
  local class=${lower:0:base}
  if ((base > 10)); then
    class+=${upper:10:base-10}
  fi
  local re="^[+-]?[$class]+$"
  if ! [[ $s =~ $re ]]; then
    echo "parse_integer: invalid integer for base $base: '$s'" >&2
    return 1
  fi
  # Do not use $((base#digits)): shell arithmetic wraps on overflow. Add the
  # digits toward the negative side, so the minimum fits, and check each step.
  local min=$((-9223372036854775807 - 1))
  local digits=${s#[+-]} v=0 i c rest d
  for ((i = 0; i < ${#digits}; i++)); do
    c=${digits:i:1}
    rest=${lower%%"$c"*}
    if ((${#rest} == 36)); then
      rest=${upper%%"$c"*}
    fi
    d=${#rest}
    if ((v < (min + d) / base)); then
      echo "parse_integer: integer out of range: '$s'" >&2
      return 2
    fi
    v=$((v * base - d))
  done
  if [[ $s != -* ]]; then
    if ((v == min)); then
      echo "parse_integer: integer out of range: '$s'" >&2
      return 2
    fi
    v=$((-v))
  fi
  echo "$v"
}
test_parse_integer.bats 241 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/parse-an-integer/.

setup() {
  source "$BATS_TEST_DIRNAME/parse_integer.sh"
  ZEROS=$(printf '0%.0s' {1..5000})
  NINES=$(printf '9%.0s' {1..5000})
}

@test "decimal" {
  run parse_integer '42' 10
  [ "$status" -eq 0 ]
  [ "$output" = "42" ]
}

@test "negative" {
  run parse_integer '-17' 10
  [ "$status" -eq 0 ]
  [ "$output" = "-17" ]
}

@test "hex" {
  run parse_integer 'ff' 16
  [ "$status" -eq 0 ]
  [ "$output" = "255" ]
}

@test "binary" {
  run parse_integer '101010' 2
  [ "$status" -eq 0 ]
  [ "$output" = "42" ]
}

@test "base-36" {
  run parse_integer 'zz' 36
  [ "$status" -eq 0 ]
  [ "$output" = "1295" ]
}

@test "plus-sign" {
  run parse_integer '+5' 10
  [ "$status" -eq 0 ]
  [ "$output" = "5" ]
}

@test "negative-zero" {
  run parse_integer '-0' 10
  [ "$status" -eq 0 ]
  [ "$output" = "0" ]
}

@test "zero" {
  run parse_integer '0' 10
  [ "$status" -eq 0 ]
  [ "$output" = "0" ]
}

@test "leading-zeros" {
  run parse_integer '007' 10
  [ "$status" -eq 0 ]
  [ "$output" = "7" ]
}

@test "many-leading-zeros" {
  run parse_integer "${ZEROS}42" 10
  [ "$status" -eq 0 ]
  [ "$output" = "42" ]
}

@test "max" {
  run parse_integer '9223372036854775807' 10
  [ "$status" -eq 0 ]
  [ "$output" = "9223372036854775807" ]
}

@test "min" {
  run parse_integer '-9223372036854775808' 10
  [ "$status" -eq 0 ]
  [ "$output" = "-9223372036854775808" ]
}

@test "max-hex" {
  run parse_integer '7fffffffffffffff' 16
  [ "$status" -eq 0 ]
  [ "$output" = "9223372036854775807" ]
}

@test "min-binary" {
  run parse_integer '-1000000000000000000000000000000000000000000000000000000000000000' 2
  [ "$status" -eq 0 ]
  [ "$output" = "-9223372036854775808" ]
}

@test "upper-case" {
  run parse_integer 'FF' 16
  [ "$status" -eq 0 ]
  [ "$output" = "255" ]
}

@test "mixed-case" {
  run parse_integer 'Zz' 36
  [ "$status" -eq 0 ]
  [ "$output" = "1295" ]
}

@test "above-safe-integer" {
  run parse_integer '9007199254740993' 10
  [ "$status" -eq 0 ]
  [ "$output" = "9007199254740993" ]
}

@test "empty" {
  run parse_integer '' 10
  [ "$status" -eq 1 ]
}

@test "sign-only" {
  run parse_integer '-' 10
  [ "$status" -eq 1 ]
}

@test "plus-only" {
  run parse_integer '+' 10
  [ "$status" -eq 1 ]
}

@test "double-sign" {
  run parse_integer '+-5' 10
  [ "$status" -eq 1 ]
}

@test "leading-space" {
  run parse_integer ' 42' 10
  [ "$status" -eq 1 ]
}

@test "trailing-space" {
  run parse_integer '42 ' 10
  [ "$status" -eq 1 ]
}

@test "trailing-newline" {
  run parse_integer $'42\n' 10
  [ "$status" -eq 1 ]
}

@test "trailing-garbage" {
  run parse_integer '42px' 10
  [ "$status" -eq 1 ]
}

@test "underscore" {
  run parse_integer '1_000' 10
  [ "$status" -eq 1 ]
}

@test "thousands-separator" {
  run parse_integer '1,000' 10
  [ "$status" -eq 1 ]
}

@test "decimal-point" {
  run parse_integer '4.0' 10
  [ "$status" -eq 1 ]
}

@test "exponent" {
  run parse_integer '1e3' 10
  [ "$status" -eq 1 ]
}

@test "hex-prefix" {
  run parse_integer '0x1A' 16
  [ "$status" -eq 1 ]
}

@test "binary-prefix" {
  run parse_integer '0b101' 2
  [ "$status" -eq 1 ]
}

@test "digit-outside-base" {
  run parse_integer '102' 2
  [ "$status" -eq 1 ]
}

@test "letter-outside-base" {
  run parse_integer 'fg' 16
  [ "$status" -eq 1 ]
}

@test "arabic-indic-digits" {
  run parse_integer $'\xd9\xa1\xd9\xa2' 10
  [ "$status" -eq 1 ]
}

@test "fullwidth-digits" {
  run parse_integer $'\xef\xbc\x91\xef\xbc\x92' 10
  [ "$status" -eq 1 ]
}

@test "kelvin-sign" {
  run parse_integer $'\xe2\x84\xaa' 36
  [ "$status" -eq 1 ]
}

@test "max-plus-one" {
  run parse_integer '9223372036854775808' 10
  [ "$status" -eq 2 ]
}

@test "min-minus-one" {
  run parse_integer '-9223372036854775809' 10
  [ "$status" -eq 2 ]
}

@test "two-to-the-64" {
  run parse_integer '18446744073709551616' 10
  [ "$status" -eq 2 ]
}

@test "hex-sign-bit" {
  run parse_integer '8000000000000000' 16
  [ "$status" -eq 2 ]
}

@test "hex-all-ones" {
  run parse_integer 'ffffffffffffffff' 16
  [ "$status" -eq 2 ]
}

@test "min-times-ten" {
  run parse_integer '-92233720368547758080' 10
  [ "$status" -eq 2 ]
}

@test "many-digits" {
  run parse_integer "$NINES" 10
  [ "$status" -eq 2 ]
}

References

  1. The Python Standard Library, Built-in Functions, int, class int(x, base=10): white space, underscores, Unicode decimal digits, the prefixes 0b, 0o and 0x, the allowed bases 0 and 2 to 36
  2. The Python Standard Library, Built-in Types, Integer string conversion length limitation, the default limit of 4300 digits; the ValueError
  3. The Python Standard Library, Built-in Exceptions, OverflowError
  4. ECMAScript Language Specification, parseInt (string, radix)
  5. MDN Web Docs, Number.MAX_SAFE_INTEGER, Description
  6. Java SE 25 API, java.lang.Long, parseLong(String, int)
  7. Java SE 25 API, java.lang.Character, digit(char, int)
  8. .NET API reference, Int64.Parse, Parse(String, NumberStyles, IFormatProvider), Exceptions
  9. .NET API reference, NumberStyles, Fields (AllowLeadingSign, Integer)
  10. .NET API reference, Convert.ToInt64(String, Int32), Exceptions; Remarks
  11. Go standard library, package strconv, ParseInt; NumError; ErrRange; ErrSyntax
  12. The Rust Standard Library, primitive type i64, from_str_radix (Panics)
  13. The Rust Standard Library, std::num::IntErrorKind, Empty, InvalidDigit, PosOverflow, NegOverflow
  14. The Open Group, POSIX.1-2024, strtol, strtoll, Description; Return Value; Errors; Application Usage
  15. cppreference.com, std::from_chars, Description; Return value
  16. GNU Bash Reference Manual, Shell Arithmetic, fixed-width integers with no check for overflow; base#n; a shell variable in an expression
  17. Unicode Character Database, CaseFolding.txt, 212A; C; 006B; # KELVIN SIGN
  18. The Open Group, POSIX.1-2024, isalnum, isalnum_l, Description
  19. The Open Group, POSIX.1-2024, Base Definitions, Regular Expressions, 9.3.5 RE Bracket Expression, range expressions

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (cpp)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (csharp)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (go)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (java)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (javascript)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (python)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (rust)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (typescript)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source

The native tests pass in 9 of 10 languages in this build.