next up previous
Next: Floating Point Up: Characters Previous: Characters

Example: Character to Numeric Conversion

The following program performs the same function as the 'get N' instruction using character input:

dec1 4% cat ~cs301/fig4.7.s

#
# Figure 4.7: SAL program simulates 'get int' instruction
#	by converting a string of digits to an integer.
#
	.data
c:	.byte			# input character
int:	.word			# result of conversion
digit:	.word			# numeric value of character
prompt:	.asciiz "Enter a number: "
numis:	.asciiz "The number is: "
nl:	.byte	'\n'

	.text
__start: move	int, 0		# initialize result
	puts prompt		# prompt for input 
loop:	get	c		# get a character
	bgt	c, '9', print	# check that character
        blt	c, '0', print   # is a digit
	sub	digit, c, '0'	# convert character to unsigned
	mul	int, int, 10	# int = 10 * int 
	add	int, int, digit	#	+ digit
	b	loop
print:	puts	numis		# print the number
	put	int
	put 	nl
	done

dec1 5% spim

SPIM Version 4.4.2, Release:  April 22, 1993
Copyright 1990-92 by James R. Larus (larus@cs.wisc.edu)
Modified to read SAL code by Scott Kempf (scottk@cs.wisc.edu)
See the file COPYING for license information

(spim) load "fig4.7.s"
(spim) run
Enter a number: 12345
The number is: 12345
(spim) exit
 
dec1 6% 



CS 301 Class Account
Mon Sep 14 23:38:35 ADT 1998