Algorithmscharacter to integer conversion

Character to Integer Conversion (Digits and Bases)

TT
Testlaa Team
May 14, 20261 min read

Converting digit characters to integers uses int(ch) for decimal, or int(ch, 16) for hex. For whole numeric strings, int(s) parses arbitrary length (subject to memory).

Why this shows up in the real world

Spreadsheet imports parse '00042' as 42 when numeric mode is on. Embedded systems read ASCII digit bytes and accumulate values.

Core idea (explained for students)

Digit char to int: ord(ch) - ord('0') highlights ASCII layout; int(ch) is clearer. For signed strings, strip +/- first and track sign separately.

Try this in Python

def parse_unsigned(s: str) -> int:
    n = 0
    for ch in s:
        if not ch.isdigit():
            raise ValueError
        n = n * 10 + (ord(ch) - ord("0"))
    return n


print(parse_unsigned("904"))

Common mistakes

  • int('') raises—guard empties.
  • Non-digit characters raise ValueError—validate first.

Key takeaways

  • Validate with ch.isdigit() (or stricter isdecimal) before int(ch) when input is messy.
  • For speed on guaranteed digits, ord subtraction avoids exception machinery.

Tags:

StringsPythonStudents