int10.py

#!/usr/bin/env python
#
# Generate a number from a string in base 10
# without using the built-in  int(...) function.
#
# Author:  Yotam Medini  [email protected] -- Created: 2006/February/20
#

import sys


def int10(s):
    ok = True  # s is OK
    n = 0
    digits10 = "0123456789"
    for c in s:  # Go thru the characters in s from left to right
        # Find the place of c in digits10
        ci = 0
        while ci < 10 and digits10[ci] != c:
            ci += 1
        if ci == 10:
            # Ooops c is not a legal digit!
            ok = False
        else:
            n = 10*n + ci  # grow the number with the new digit
    if not ok:
        n = -1  # This will stand for "Bad Number"
    return n


def usage_exit(a0, rc):
    sys.stderr.write(
"""
Usage:
  %s <snum1> [<snum2> ... <snumN>]
"""[1:] % a0)
    sys.exit(rc)


# Begin program
if len(sys.argv) < 2:
    usage_exit(sys.argv[0], 1)
for s in sys.argv[1:]:
    n = int10(s)
    sys.stdout.write('int10(string = "%s") = %d\n' % (s, n))
sys.exit(0)

Generated by GNU enscript 1.6.4.