100 likes | 185 Views
Adding a list of integers. Here apply our previous lessons about command-line arguments and numeric conversions. Our ‘add.s’ demo. This program allows a user to type a list of unsigned integers as program arguments Example: $ ./add 11 22 33
E N D
Adding a list of integers Here apply our previous lessons about command-line arguments and numeric conversions
Our ‘add.s’ demo • This program allows a user to type a list of unsigned integers as program arguments • Example: $ ./add 11 22 33 • Then the program converts these strings of digit-characters into the integer values they represent, adds those integers, does a number-to-string conversion and shows us the result: ‘The total is 66’
The stack upon entry command-line: $ ./add 11 22 33 application’s stack NULL argv[3] argv[2] argv[1] argv[0] 4 SS:RSP
Symbols and data # manifest constants (to make code understandable) .equ STDOUT, 1 # device-file ID-number .equ sys_write, 1 # system-call ID-number .equ sys_exit, 60 # system-call ID-number # static data (for storing data values in memory) .section .data ten: .quad 10 # the decimal-system radix total: .quad 0 # for sum of the arguments msg: .ascii “The total is “ # title for program’s output buf: .ascii “ \n” # buffer for the result-string len: .quad . – msg # length of output message
‘atoi’ and ‘itoa’ • We employ a pair of subroutines that will perform the needed data-conversions: • From a digit-string to an unsigned integer • From an unsigned integer to a digit-string • We call ‘atoi’ for doing ascii-to-integer • We call ‘itoa’ for doing integer-to-ascii
Project #1 • Can you design modifications of these two subroutines so that the ‘add.s’ program is able to correctly handle signedintegers? • Example: $ ./add 115 -50 10 -200 The total is -125
‘unsigned’ versus ‘signed’ 8 9 7 -8 -7 7 6 10 6 -6 11 5 -5 5 12 4 -4 4 13 3 -3 3 2 14 2 -2 15 1 -1 1 0 0
Unsigned interpretation 7 6 5 4 3 2 1 0 Position: 128 64 32 16 8 4 2 1 Weight: Digit: 1 0 0 1 1 1 0 1 128 + 0 + 0 + 16 + 8 + 4 + 0 + 1 = 157
Signed interpretation 7 6 5 4 3 2 1 0 Position: -128 64 32 16 8 4 2 1 Weight: Digit: 1 0 0 1 1 1 0 1 -128 + 0 + 0 + 16 + 8 + 4 + 0 + 1 = - 99
Negating an 8-bit integer • For the ‘twos complement’ representation of signed integers, you can quickly obtain the negative of a number by applying this two-step rule: “Flip the bits, then add one” Example: negative seven = 11111001 Flip the bits: 00000110 Now add one: +1 -------------------------- Result: positive seven = 00000111