Here you'll find all the code I've written in the T13A tutorials, as well as some possibly useful information:
cs1521@cse.unsw.edu.au
x.cooney@unsw.edu.au
print_diary.c
// Write a C program, print_diary.c, which prints the contents
// of the file $HOME/.diary to stdout
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// the path we want to open is
// "<whatever is in the HOME environment variable>/.diary"
int main(void) {
char *home_value = getenv("HOME");
char *suffix = "/.diary";
printf("home_value = \"%s\"\n", home_value);
int path_size = strlen(home_value) + strlen(suffix) + 1;
char *path = malloc(path_size);
if (path == NULL) {
perror("malloc");
return 1;
}
snprintf(path, path_size, "%s%s", home_value, suffix);
printf("path = \"%s\"\n", path);
FILE *stream = fopen(path, "r");
if (stream == NULL) {
perror(path);
return 1;
}
free(path);
int byte;
while ((byte = fgetc(stream)) != EOF) {
putchar(byte);
}
fclose(stream);
}
chmod_if_public_write.c
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
// ./chmod_if_public_write print_diary.c file code.txt
void chmod_if_public_write(char *path);
int main(int argc, char *argv[]) {
for (int i = 1; i < argc; i++) {
chmod_if_public_write(argv[i]);
}
}
void chmod_if_public_write(char *path) {
// 1. get the permissions
struct stat statbuf;
if (stat(path, &statbuf) != 0) {
perror(path);
return;
}
// 101110000
// 000000010 &
// 000000000
if ((statbuf.st_mode & S_IWOTH) == 0) {
printf("%s does not have public write bit!\n", path);
return;
}
// 111111101
if (chmod(path, statbuf.st_mode & ~S_IWOTH) != 0) {
perror(path);
} else {
printf("public write bit removed from %s!\n", path);
}
}
first_line.c
// Write a C program, first_line.c, which is given one command-line argument,
// the name of a file, and which prints the first line of that file to stdout.
// If given an incorrect number of arguments, or if there was an error opening
// the file, it should print a suitable error message.
#include <stdio.h>
#include <stdlib.h>
// ./first_line lines.txt
// argv[0] = "./first_line"
// argv[1] = "lines.txt"
// argc = 2
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: ./first_line <file>\n");
exit(1);
}
char *path = argv[1];
FILE *stream = fopen(path, "r");
if (stream == NULL) {
perror(path);
exit(1);
}
// functions to read from files: fgetc, fgets, fscanf, fread
// functions to write to files: fputc, fputs, fprintf, fwrite
int byte;
while ((byte = fgetc(stream)) != EOF) {
putchar(byte);
if (byte == '\n') {
break;
}
}
fclose(stream);
}
float_weird.c
#include <stdio.h>
int main(void) {
float a = 0.1;
float b = 0.2;
float sum = a + b;
printf("a = %.15g, b = %.15g and sum = %.15g\n", a, b, sum);
printf("And sum == 0.3 is: %d\n", sum == 0.3);
}
get_bit_groups.c
#include <stdint.h>
typedef struct six_bit_groups {
uint8_t middle_bits;
uint8_t lower_bits;
} six_bit_groups_t;
/*
Example:
01100010 10101101 11001100 10010011
^^^ ^^^ ^^^^^^
middle lower
= 46 = 19
01100010 10101101 11001100 10010011 <-- value
00000000 00000000 00000000 01000000 <-- 1 << 6
00000000 00000000 00000000 00111111 <-- (1 << 6) - 1
00000000 00000000 00000000 00111111 <-- mask
-----------------------------------------
00000000 00000000 00000000 00010011 <-- value & mask
*/
six_bit_groups_t get_bit_groups(uint32_t value) {
six_bit_groups_t result;
// uint32_t mask = 0b111111;
uint32_t mask = 0x3F;
// uint32_t mask = 63;
// uint32_t mask = (1 << 6) - 1;
result.lower_bits = value & mask;
result.middle_bits = (value >> 13) & mask;
// uint32_t middle_six_bits = (value & (mask << 13)) >> 13;
return result;
}
reverse_bits.c
#include <assert.h>
#include <stdio.h>
#include <stdint.h>
// Reverse a 32 bit value
uint32_t reverse_bits(uint32_t value) {
uint32_t answer = 0;
for (int i = 0; i < 32; i++) {
// 1. check if bit `i` in `value` is a 1?
uint32_t mask = 1;
mask = mask << i;
if ((mask & value) != 0) {
// 2. ==> if it is, set the 'opposite' bit in
// `answer` to a 1
int opposite_bit_pos = 31 - i;
uint32_t opposite_bit = 1;
opposite_bit = opposite_bit << opposite_bit_pos;
answer = answer | opposite_bit;
}
}
return answer;
}
int main(void) {
assert(reverse_bits(0xFFFFFFFF) == 0xFFFFFFFF);
assert(reverse_bits(0x00000000) == 0x00000000);
assert(reverse_bits(0x1) == 0x80000000);
assert(reverse_bits(0x2) == 0x40000000);
assert(reverse_bits(0x01234567) == 0xE6A2C480);
printf("All tests passed!\n");
return 0;
}
examples.txt
uint16_t a = 0x5566, b = 0xAAAA, c = 0x0001;
a) a | b
b) a & b
c) a ^ b
d) a & ~b
e) c << 6
f) a >> 4
g) a & (b << 1)
h) b | c
i) a & ~c
rec_max.c
#include <stdio.h>
// C function to find the largest element in an array, recursively.
// Returns the value of the largest element in the array.
//
// array: Array to search
// length: Number of elements in the array
int rec_max(int array[], int length) {
int first_element = array[0];
if (length == 1) {
// Handle the base-case of the recursion, at the end of the array.
return first_element;
} else {
// Recurse on the rest of the array.
// Finds the largest element after first_element in the array.
int max_so_far = rec_max(&array[1], length - 1);
// Compare this element with the largest element after it in the array.
if (first_element > max_so_far) {
max_so_far = first_element;
}
return max_so_far;
}
}
int main(void) {
int data[10] = {2, -3, 5, 4, 42, 2, 8, 4, 1, 9};
printf("%d\n", rec_max(data, 10));
return 0;
}
rec_max.s
########################################################################
# COMP1521 24T3 -- ...
#
#
# !!! IMPORTANT !!!
# Before starting work on the assignment, make sure you set your tab-width to 8!
# It is also suggested to indent with tabs only.
# Instructions to configure your text editor can be found here:
# https://cgi.cse.unsw.edu.au/~cs1521/24T3/resources/mips-editors.html
# !!! IMPORTANT !!!
#
#
# This program was written by Xavier Cooney (z5417087)
# on INSERT-DATE-HERE. INSERT-SIMPLE-PROGRAM-DESCRIPTION-HERE
#
# Version 1.0 (12-06-2023): Team COMP1521 <cs1521@cse.unsw.edu.au>
#
########################################################################
.text
rec_max:
# Args:
# - $a0: int array[]
# - $a1: int length
#
# Returns:
# - $v0: const char *
#
# Frame: [$ra, $s0]
# Uses: [$t0, $t1, $t3, $s0, $a0, $a1, $v0, $ra]
# Clobbers: [$t0, $t1, $t3, $a0, $a1, $v0]
#
# Locals:
# - array: $t0
# - length: $t1
# - first_element: $s0
# - max_so_far: $t3
#
# Structure:
# current_player_str
# -> [prologue]
# -> body
# -> [epilogue]
# int rec_max(int array[], int length) {
rec_max__prologue:
begin
push $ra
push $s0
rec_max__body:
move $t0, $a0
move $t1, $a1
# int first_element = array[0];
lw $s0, ($t0)
bne $t1, 1, rec_max__length_ne_1 # if (length == 1) {
# return first_element;
move $v0, $s0
b rec_max__epilogue
rec_max__length_ne_1: # } else {
# int max_so_far = rec_max(&array[1], length - 1);
addi $a0, $t0, 4 # array + 4
sub $a1, $t1, 1 # length - 1
jal rec_max
move $t3, $v0
ble $s0, $t3, rec_max__ret_max_so_far # if (first_element > max_so_far) {
# max_so_far = first_element;
move $t3, $s0
rec_max__ret_max_so_far: # }
# return max_so_far;
move $v0, $t3
rec_max__epilogue: # }
pop $s0
pop $ra
end
jr $ra
main:
main__prologue:
push $ra
main__body:
la $a0, test_data
li $a1, 10
jal rec_max # result = rec_max(test_data, 10)
move $a0, $v0
li $v0, 1 # syscall 1: print_int
syscall # printf("%d", result);
li $v0, 11 # syscall 11: print_char
li $a0, '\n'
syscall # printf("%c", '\n');
li $v0, 0
main__epilogue:
pop $ra
jr $ra # return 0;
.data
test_data:
.word 2, -3, 5, 4, 42, 2, 8, 4, 1, 9
topography.c
// A topographic map!
// This helpful tool will tell explorers how much they need to climb to
// reach various points of interest.
// Given an array of points, `my_points`, it can look up individual cells
// in the 2D map and print their height.
#include <stdio.h>
#define NUM_ROWS 5
#define NUM_COLS 5
#define N_POINTS 4
// 2D representation of a point, stored as a single struct
struct point2D {
int row;
int col;
} typedef point2D_t;
// 2D grid representing the height data for an area.
int topography_grid[NUM_ROWS][NUM_COLS] = {
{ 0, 1, 1, 2, 3 },
{ 1, 1, 2, 3, 4 },
{ 1, 2, 3, 5, 7 },
{ 3, 3, 4, 5, 6 },
{ 3, 4, 5, 6, 7 },
};
// Points of interest to print heights for, as a 1D array.
point2D_t my_points[N_POINTS] = {
{ 1, 2 },
{ 2, 3 },
{ 0, 0 },
{ 4, 4 },
};
int main(void) {
for (int i = 0; i < N_POINTS; i++) {
int row = my_points[i].row;
int col = my_points[i].col;
int height = topography_grid[row][col];
printf("Height at %d,%d=%d\n", row, col, height);
}
return 0;
}
topography.s
# A topographic map!
# Constants
NUM_ROWS = 5
NUM_COLS = 5
N_POINTS = 4
SIZEOF_INT = 4
SIZEOF_POINT2D = 8
POINT2D_ROW_OFFSET = 0
POINT2D_COL_OFFSET = 4
.data
# 2D grid representing the height data for an area.
topography_grid:
.word 0, 1, 1, 2, 3
.word 1, 1, 2, 3, 4
.word 1, 2, 3, 5, 7
.word 3, 3, 4, 5, 6
.word 3, 4, 5, 6, 7
# Points of interest to print heights for, as a 1D array of point2D_t structs.
# Note the memory layout of this array: each element requires 8 bytes, not 4.
my_points:
.word 1, 2
.word 2, 3
.word 0, 0
.word 4, 4
height_str:
.asciiz "Height at "
.text
main:
# Registers:
# - $t0: int i, the loop counter
# - $t1: row of the current point
# - $t2: col of the current point
# - $t3: height of the current point
# - $t4: temporary result for array indexing
# - $t5: temporary result for array indexing
# Loop over all elements, and print their data
points_loop_init: # for (int i = 0; i < N_POINTS; i++) {
li $t0, 0 # $t0 = 0
points_loop_cond:
bge $t0, N_POINTS, points_loop_end # if (i >= N_POINTS)
# We have i in $t0
# We want row in $t1
# We want col in $t2
# We want height in $t3
# int row = my_points[i].row;
la $t4, my_points
mul $t5, $t0, SIZEOF_POINT2D
add $t4, $t4, $t5
lw $t1, POINT2D_ROW_OFFSET($t4)
# int col = my_points[i].col;
la $t4, my_points
mul $t5, $t0, SIZEOF_POINT2D
add $t4, $t4, $t5
lw $t2, POINT2D_COL_OFFSET($t4)
# int height = topography_grid[row][col];
# &data[row][col] = &data + (row * NUM_COLUMNS + col) * sizeof(element)
la $t4, topography_grid
mul $t5, $t1, NUM_COLS
add $t5, $t5, $t2
mul $t5, $t5, SIZEOF_INT
add $t4, $t4, $t5
lw $t3, ($t4)
# printf("Height at %d,%d=%d\n", row, col, height);
li $v0, 4 # $v0 = 4 (print string)
la $a0, height_str # load address of height_str into $a0
syscall # print height_str
li $v0, 1 # $v0 = 1 (print int)
move $a0, $t1 # $a0 = row
syscall # print row
li $v0, 11 # $v0 = 11 (print ASCII character)
li $a0, ',' # $a0 = ','
syscall # print ','
li $v0, 1 # $v0 = 1 (print int)
move $a0, $t2 # $a0 = col
syscall # print col
li $v0, 11 # $v0 = 11 (print ASCII character)
li $a0, '=' # $a0 = '='
syscall # print '='
li $v0, 1 # $v0 = 1 (print int)
move $a0, $t3 # $a0 = height
syscall # print height
li $v0, 11 # $v0 = 11 (print ASCII character)
li $a0, '\n' # $a0 = '\n'
syscall # print '\n'
points_loop_iter:
addi $t0, $t0, 1 # i++
b points_loop_cond # branch to points_loop_cond
points_loop_end:
jr $ra # return 0;
print_array.c
// A simple program that will print 10 numbers from an array
#define N_SIZE 10
#include <stdio.h>
// int -> word
// char -> byte
// short -> halves
int numbers[N_SIZE] = {
3, 1, 4, 1, 5, 9, 2, 6, 5, 3
};
int main(void) {
for (int i = 0; i < N_SIZE; i++) {
int num = numbers[i];
printf("%d\n", num);
}
}
print_array.s
N_SIZE = 10
main:
# Locals:
# i: $t0
# num: $t1
loop__init:
# int i = 0;
li $t0, 0
loop__cond:
bge $t0, N_SIZE, loop__end
loop__body:
# int num = numbers[i];
# 1. we need to get the address
# of the object we're accessing
# &numbers[i] = &numbers + sizeof(element) * i
la $t2, numbers # &numbers
mul $t3, 4, $t0 # 4 * i
add $t2, $t2, $t3 # &numbers + 4 * i
# == &numbers[i]
# 2. is it a load or a store access?
# it's a load!
# 3. is it a byte, half or word?
# it's a word
lw $t1, ($t3)
# printf("%d\n", num);
move $a0, $t1
li $v0, 1
syscall
li $a0, '\n'
li $v0, 11
syscall
loop__increment:
# i++;
addi $t0, $t0, 1
b loop__cond
loop__end:
li $v0, 0
jr $ra
.data
numbers:
# int numbers[N_SIZE] = {
# 3, 1, 4, 1, 5, 9, 2, 6, 5, 3
# };
.word 3, 1, 4, 1, 5, 9, 2, 6, 5, 3
read_array.c
// A simple program that will read 10 numbers into an array
#define N_SIZE 5
#include <stdio.h>
int main(void) {
int i;
int numbers[N_SIZE];
i = 0;
while (i < N_SIZE) {
scanf("%d", &numbers[i]);
i++;
}
i = 0;
while (i < N_SIZE) {
int num = numbers[i];
printf("%d\n", num);
i++;
}
}
read_array.s
N_SIZE = 5
main:
# Locals:
# i: $t0
# num: $t1
loop_read__init:
li $t0, 0
loop_read__cond:
bge $t0, N_SIZE, loop_read__end
loop_read__body:
# scanf("%d", &numbers[i]);
# numbers[i] = read_int()
li $v0, 5
syscall
move $t4, $v0
la $t2, numbers # &numbers
mul $t3, 4, $t0 # 4 * i
add $t2, $t2, $t3 # &numbers + 4 * i
# == &numbers[i]
# it's a store!
sw $t4, ($t2)
loop_read__step:
addi $t0, $t0, 1
b loop_read__cond
loop_read__end:
loop_print__init:
# int i = 0;
li $t0, 0
loop_print__cond:
bge $t0, N_SIZE, loop_print__end
loop_print__body:
# int num = numbers[i];
# 1. we need to get the address
# of the object we're accessing
# &numbers[i] = &numbers + sizeof(element) * i
la $t2, numbers # &numbers
mul $t3, 4, $t0 # 4 * i
add $t2, $t2, $t3 # &numbers + 4 * i
# == &numbers[i]
# 2. is it a load or a store access?
# it's a load!
# 3. is it a byte, half or word?
# it's a word
lw $t1, ($t2)
# printf("%d\n", num);
move $a0, $t1
li $v0, 1
syscall
li $a0, '\n'
li $v0, 11
syscall
loop_print__increment:
# i++;
addi $t0, $t0, 1
b loop_print__cond
loop_print__end:
li $v0, 0
jr $ra
.data
numbers:
.space 4*N_SIZE
hello.s
# Write a MIPS assembly program which prints out "Hello, world!"
main:
la $a0, hello_world_str
li $v0, 4 # $v0 = 4
syscall
li $v0, 0
jr $ra # return 0;
.data
hello_world_str:
.asciiz "Hello, world!\n"
square.c
// Prints the square of a number
#include <stdio.h>
int main(void) {
int x, y;
printf("Enter a number: ");
scanf("%d", &x);
y = x * x;
printf("%d", y);
putchar('\n');
}
square.s
main:
# Locals:
# x: $t1
# y: $t2
# printf("Enter a number: ");
la $a0, enter_a_number_str
li $v0, 4
syscall
# scanf("%d", &x);
li $v0, 5
syscall
move $t1, $v0
# y = x * x;
mul $t2, $t1, $t1
# printf("%d", y);
li $v0, 1
move $a0, $t2
syscall
# putchar('\n');
li $v0, 11
li $a0, '\n'
syscall
# return 0;
li $v0, 0
jr $ra
.data
enter_a_number_str:
.asciiz "Enter a number: "
bounded_square.c
// Squares a number, unless its square is too big for a 32-bit integer.
// If it is too big, prints an error message instead.
#include <stdio.h>
#define SQUARE_MAX 46340
int main(void) {
int x, y;
printf("Enter a number: ");
scanf("%d", &x);
// if (x > SQUARE_MAX) {
if (x <= SQUARE_MAX) { goto print_square; }
square_too_big:
printf("square too big for 32 bits\n");
goto epilogue;
// } else {
print_square:
y = x * x;
printf("%d\n", y);
// }
epilogue:
return 0;
}
bounded_square.s
SQUARE_MAX = 46340
main:
# Locals:
# x: $t1
# y: $t2
# printf("Enter a number: ");
la $a0, enter_a_number_str
li $v0, 4
syscall
# scanf("%d", &x);
li $v0, 5
syscall
move $t1, $v0
ble $t1, SQUARE_MAX, print_square
li $v0, 4
la $a0, square_too_big_str
syscall
b epilogue
print_square:
# y = x * x;
mul $t2, $t1, $t1
# printf("%d", y);
li $v0, 1
move $a0, $t2
syscall
# putchar('\n');
li $v0, 11
li $a0, '\n'
syscall
epilogue:
# return 0;
li $v0, 0
jr $ra
.data
enter_a_number_str:
.asciiz "Enter a number: "
square_too_big_str:
.asciiz "square too big for 32 bits\n"
for.c
// Print every third number from 24 to 42.
#include <stdio.h>
int main(void) {
for (int x = 24; x < 42; x += 3) {
printf("%d\n", x);
}
}
No code yet! If the tutorial is over, please remind Xavier to run the upload script :)