1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
|
# CSCI 424, Homework 2
# switch to the Data segment
.data
# global data is defined here
# Don't forget the backslash-n (newline character)
Homework:
.asciiz "CSCI 424 Homework 2\n"
Name_1:
.asciiz "Adam\n"
Name_2:
.asciiz "Carpenter\n"
# switch to the Text segment
.text
# the program is defined here
.globl main
main:
# Whose program is this?
la $a0, Homework
jal Print_string
la $a0, Name_1
jal Print_string
la $a0, Name_2
jal Print_string
# int i, n = 2;
# for (i = 0; i <= 16; i++)
# {
# ... calculate n from i
# ... print i and n
# }
# register assignments
# $s0 i
# $s1 n
# $a0 argument to Print_integer, Print_string
# add to this list if you use any other registers
# ---My New Registers---
# $s2 bit
# $t0 temp (temporary)
# ----------------------
# initialization
li $s1, 2 # n = 2
# for (i = 0; i <= 16; i++)
li $s0, 0 # i = 0
bgt $s0, 16, bottom
top:
# calculate n from i
# Your part starts here
# ------Solution in C code--------
# n = 0;
# int bit;
# for (bit = 0; bit < 32; bit++) {
# temp = i >> bit;
# temp = temp & 1;
# n = n + temp;
# }
# --------------------------------
li $s1, 0 # n = 0
li $s2, 0 # bit = 0
bitloop:
srav $t0, $s0, $s2 # temp = i >> bit
andi $t0, $t0, 1 # temp = temp & 1
add $s1, $s1, $t0 # n = n + temp
add $s2, $s2, 1 # bit++
blt $s2, 32, bitloop # if bit < 32 goto bitloop
# Your part ends here
# print i and n
move $a0, $s0 # i
jal Print_integer
la $a0, sp # space
jal Print_string
move $a0, $s1 # n
jal Print_integer
la $a0, cr # newline
jal Print_string
# for (i = 0; i <= 16; i++)
add $s0, $s0, 1 # i++
ble $s0, 16, top # i <= 16
bottom:
la $a0, done # mark the end of the program
jal Print_string
jal Exit # end the program, no explicit return status
# switch to the Data segment
.data
# global data is defined here
sp:
.asciiz " "
cr:
.asciiz "\n"
done:
.asciiz "All done!\n"
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Wrapper functions around some of the system calls
# See P&H COD, Fig. A.9.1, for the complete list.
# switch to the Text segment
.text
.globl Print_integer
Print_integer: # print the integer in register a0
addi $v0, $zero, 1
syscall
jr $ra
.globl Print_string
Print_string: # print the string whose starting address is in register a0
addi $v0, $zero, 4
syscall
jr $ra
.globl Exit
Exit: # end the program, no explicit return status
addi $v0, $zero, 10
syscall
jr $ra
.globl Exit2
Exit2: # end the program, with return status from register a0
addi $v0, $zero, 17
syscall
jr $ra
|