int16.py
#!/usr/bin/env python
#
# Generate a number from a string in Hexadecimal display (lower case).
# without using the built-in int(...) function.
#
# Author: Yotam Medini [email protected] -- Created: 2006/February/26
#
import sys
def int16(s):
ok = True # s is OK
n = 0
digits = "0123456789abcdef"
for c in s: # Go thru the characters in s from left to right
# Find the place of c in digits
ci = 0
while ci < 16 and digits[ci] != c:
ci += 1
if ci == 16:
# Ooops c is not a legal digit!
ok = False
else:
n = 16*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 = int16(s)
sys.stdout.write('int16(string = "%s") = %d\n' % (s, n))
sys.exit(0)
Generated by GNU enscript 1.6.4.