Here you'll find all the code I've written in the H13A 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 <complex.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
// open the file
char *home = getenv("HOME");
printf("home = \"%s\"\n", home);
char *diary_portion = "/.diary";
size_t buffer_length = strlen(home) + strlen(diary_portion) + 1;
char *buffer = malloc(buffer_length);
if (buffer == NULL) {
fprintf(stderr, "failed to allocate memory!\n");
return 1;
}
snprintf(
buffer, buffer_length,
"%s%s", home, diary_portion
);
FILE *stream = fopen(buffer, "r");
if (stream == NULL) {
perror(buffer);
return 1;
}
int byte;
while ((byte = fgetc(stream)) != EOF) {
putchar(byte);
}
fclose(stream);
free(buffer);
}
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 *pathname);
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 *pathname) {
struct stat statbuf;
if (stat(pathname, &statbuf) != 0) {
perror(pathname);
return;
}
if ((statbuf.st_mode & S_IWOTH) == 0) {
printf("%s does not have public write bit set!\n", pathname);
return;
}
mode_t new_mode = statbuf.st_mode & (~S_IWOTH);
if (chmod(pathname, new_mode) != 0) {
perror(pathname);
return;
} else {
printf("Removed public write bit from %s\n", pathname);
return;
}
}
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>
// ./first_line file.txt
// argv[0] = "./first_line"
// argv[1] = "file.txt"
int main(int argc, char *argv[]) {
// check that we have the right number of arguments
if (argc != 2) {
fprintf(stderr, "Usage: ./first_line <file>\n");
return 1;
}
char *pathname = argv[1];
FILE *stream = fopen(pathname, "r");
if (stream == NULL) {
perror(pathname);
return 1;
}
// write: fwrite, fputc, fputs, fprintf
// read: fread, fgetc, fgets, fscanf
int byte;
while ((byte = fgetc(stream)) != EOF) {
fputc(byte, stdout);
if (byte == '\n') {
break;
}
// putchar(byte);
}
// close the file for me please
return 0;
}
float_weird.c
#include <stdio.h>
int main(void) {
float a = 0.1;
float b = 0.2;
float sum = a + b;
printf("a = %.9g, b = %.9g and sum = %.9g\n", a, b, sum);
printf("And sum == 0.3 is: %d\n", sum == 0.3);
}
get_bit_groups.c
#include <stdint.h>
#include <stdio.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
*/
six_bit_groups_t get_bit_groups(uint32_t value) {
uint32_t mask = (1 << 6) - 1;
// uint32_t mask = 0b111111;
// uint32_t mask = 0x3f;
// uint32_t mask = 63;
six_bit_groups_t result;
result.lower_bits = value & mask;
result.middle_bits = (value >> ((32 - 6) / 2)) & mask;
return result;
}
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
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 result = 0;
for (int i = 0; i < 32; i++) {
uint32_t mask = 1;
// is bit `i` set to 1?
if (((value >> i) & mask) == 1) {
// bit `i` is set to 1
// set the bit at the 'mirrored' `i` in result to a 1
result |= (1u << (32 - i - 1));
} else {
// bit `i` is set to 0
// don't do anything!
}
}
return result;
}
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;
}
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;
# 1) we want to do a load
# 2) what's the address &my_points[i].row;
# &my_points[i].row = (&my_points + i * 8) + 0
la $t4, my_points # &my_points
mul $t5, $t0, SIZEOF_POINT2D # i * 8
add $t4, $t4, $t5 # (&my_points + i * 8) + 0
# = &my_points[i].row
addi $t4, $t4, POINT2D_ROW_OFFSET
lw $t1, ($t4) # row = my_points[i].row;
# int col = my_points[i].col;
# addi $t4, $t4, POINT2D_COL_OFFSET # (&my_points + i * 8) + 4
# # = &my_points[i].col
# lw $t2, ($t4) # col = my_points[i].cols;
lw $t2, POINT2D_COL_OFFSET($t4) # col = my_points[i].cols;
# int height = topography_grid[row][col];
# &topography_grid[row][col] =
# topography_grid + sizeof(element) * (NUM_COLS * row + col)
la $t4, topography_grid
mul $t5, NUM_COLS, $t1
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;
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 24T1 -- ...
#
#
# !!! 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/23T2/resources/mips-editors.html
# !!! IMPORTANT !!!
#
#
# This program was written by Xavier Cooney (z5417087)
# on 2024-03-07. awiojdoiawjd
#
# 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: [...]
# Uses: [...]
# Clobbers: [...]
#
# Locals:
# - ...
#
# Structure:
# current_player_str
# -> [prologue]
# -> body
# -> [epilogue]
# int rec_max(int array[], int length) {
# array: $t0
# length: $t1
# first_element: $s0
# max_so_far: $t3
rec_max__prologue:
# TODO
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
sub $a1, $t1, 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 # }
jr $ra
# TODO
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
read_array.c
// A simple program that will read 10 numbers into an array
#define N_SIZE 10
#include <stdio.h>
int main(void) {
int i;
int numbers[N_SIZE];
i = 0;
while (i < N_SIZE) {
scanf("%d", &numbers[i]);
// numbers[i] = read_int();
i++;
}
for (int j = 0; j < N_SIZE; j++) {
printf("%d\n", numbers[j]);
}
}
read_array.s
N_SIZE = 10
main:
# i: $t0
# j: $t0
# move $t0, $zero
li $t0, 0 # i = 0;
loop_i_cond:
bge $t0, N_SIZE, loop_i_end
# 1) is this a load or a store?
# Store
# &numbers[i] = sizeof(element) * i + numbers
mul $t1, $t0, 4 # i * 4
la $t2, numbers # numbers
add $t1, $t1, $t2 # i * 4 + numbers = &numbers[i]
# 2) what's the address we're storing at?
# Whatever is in $t1 at this
# point in the program.
# 3) How big is the value we're storing?
# int => 4 bytes => word
li $v0, 5
syscall
# The value we want to store
# is in $v0
sw $v0, ($t1) # scanf("%d", &numbers[i]);
addi $t0, $t0, 1 # i++;
b loop_i_cond
loop_i_end:
li $t0, 0
loop_j_cond:
bge $t0, N_SIZE, loop_j_end
# &numbers[i] = sizeof(element) * i + numbers
mul $t1, $t0, 4 # i * 4
la $t2, numbers # numbers
add $t1, $t1, $t2 # i * 4 + numbers = &numbers[i]
lw $a0, ($t1)
li $v0, 1
syscall
li $v0, 11
li $a0, ' '
syscall
addi $t0, $t0, 1
b loop_j_cond
loop_j_end:
li $v0, 0
jr $ra
.data
numbers:
# .word 0:10 # 0, 0, 0, ... 10 times
.space 4*10
hello.s
# MIPS assembly program that prints out "Hello, world!"
# printf("Hello, world!\n");
main:
# we want to put the number 4 in $v0
li $v0, 4 # $v0 = 4
la $a0, hello_world_str
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;
printf("Enter a number: ");
scanf("%d", &x);
int y = x * x;
printf("%d", y);
putchar('\n');
// return 0;
}
square.s
.text
main:
# x: $t0
# y: $t1
# printf("Enter a number: ");
li $v0, 4
la $a0, enter_a_number_str
syscall
# scanf("%d", &x);
li $v0, 5
syscall
move $t0, $v0 # $t0 = $v0
# int y = x * x;
mul $t1, $t0, $t0
# printf("%d", y);
li $v0, 1
move $a0, $t1
syscall
li $v0, 11
li $a0, '\n'
syscall
li $v0, 0
jr $ra # return 0;
.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 x_lte_square_max;
if (x <= SQUARE_MAX) goto x_lte_square_max;
printf("square too big for 32 bits\n");
goto epilogue;
// } else {
x_lte_square_max:
y = x * x;
printf("%d\n", y);
// }
epilogue:
return 0;
}
bounded_square.s
SQUARE_MAX = 46340
.text
main:
# x: $t0
# y: $t1
# printf("Enter a number: ");
li $v0, 4
la $a0, enter_a_number_str
syscall
# scanf("%d", &x);
li $v0, 5
syscall
move $t0, $v0 # $t0 = $v0
ble $t0, SQUARE_MAX, x_lte_square_max
# printf("square too big for 32 bits\n");
li $v0, 4
la $a0, warning_str
syscall
# goto epilogue;
b epilogue
x_lte_square_max:
# int y = x * x;
mul $t1, $t0, $t0
# printf("%d", y);
li $v0, 1
move $a0, $t1
syscall
li $v0, 11
li $a0, '\n'
syscall
epilogue:
li $v0, 0
jr $ra # return 0;
.data
enter_a_number_str:
.asciiz "Enter a number: "
warning_str:
.asciiz "square too big for 32 bits\n"
factorial.c
#include <stdio.h>
#include <stdlib.h>
// Returns n!, that is
// factorial(n) = n * (n - 1) * (n - 2) * ... * 2 * 1
// 5 * 4 * 3 * 2 * 1 = (4 * 3 * 2 * 1) * 5
int factorial_iterative(int n) {
//
int cumulative = 1;
for (int counter = n; counter != 0; counter--) {
cumulative *= counter;
}
// Ackermann
// for (; n != 0; n--) {
// cumulative = n * cumulative;
// }
return cumulative;
}
// when n > 0, factorian(n) = factorial(n - 1) * n
// factorial(0) = 1
int factorial(int n) {
if (n > 0) {
return factorial(n - 1) * n;
} else {
return 1;
}
}
int main(int argc, char *argv[]) {
int input = atoi(argv[1]);
printf("factorial(%d) = %d\n", input, factorial(input));
}
hi.c
// This code tries to say hi to the user...
#include <stdio.h>
int main(void) {
char str[10];
str[0] = 'H';
str[1] = 'i';
str[2] = '\0';
printf("%s", str);
return 0;
}