aboutsummaryrefslogtreecommitdiff
path: root/comp1521/smips/helper.c
diff options
context:
space:
mode:
authorNicolas James <Eele1Ephe7uZahRie@tutanota.com>2025-02-13 18:00:17 +1100
committerNicolas James <Eele1Ephe7uZahRie@tutanota.com>2025-02-13 18:00:17 +1100
commit98cef5e9a772602d42acfcf233838c760424db9a (patch)
tree5277fa1d7cc0a69a0f166fcbf10fd320f345f049 /comp1521/smips/helper.c
initial commit
Diffstat (limited to 'comp1521/smips/helper.c')
-rw-r--r--comp1521/smips/helper.c54
1 files changed, 54 insertions, 0 deletions
diff --git a/comp1521/smips/helper.c b/comp1521/smips/helper.c
new file mode 100644
index 0000000..ebe798b
--- /dev/null
+++ b/comp1521/smips/helper.c
@@ -0,0 +1,54 @@
+#include "helper.h"
+
+// Returns the n'th bit of a uint32_t value.
+uint32_t get_nth_bit(const uint32_t value, const int n) {
+ return (value & (1u << n)) >> n;
+}
+
+// Prints the bits of a uint32_t value.
+void print_bits(const uint32_t value) {
+ for (int i = (int)sizeof(uint32_t)*8-1; i >= 0; --i) {
+ printf("%d", get_nth_bit(value, i));
+ }
+ printf("\n");
+}
+
+// Skips past the next newline.
+// If EOF, stays on EOF so that subsequent fgetc() calls return EOF.
+void skip_past_newline(FILE *const fptr) {
+ int c = 0;
+ c = fgetc(fptr);
+ while (true) {
+ if (c == EOF) {
+ fseek(fptr, -1L, SEEK_CUR);
+ return;
+ }
+ else if (c == '\n') {
+ printf("newline\n");
+ return;
+ } else {
+ fseek(fptr, -1L, SEEK_CUR);
+ return;
+ }
+ printf("skipping char\n");
+ c = fgetc(fptr);
+ }
+}
+
+// Converts decimal values to hex obviously.
+uint32_t hex_to_decimal(const uint32_t decimal) {
+ uint32_t ret = 0;
+ for (size_t i = 0; i < sizeof(uint32_t); ++i) { // Iterate through 4 bytes.
+ uint32_t tmp = (decimal & (0xFFu << 8*i)) >> 8*i;
+ if (isalpha(tmp)) {
+ tmp -= 'a';
+ tmp += 10;
+ }
+ else if (isdigit(tmp)) {
+ tmp -= '0';
+ }
+ // There should be no other cases if the input is hex.
+ ret |= (tmp << 4*i);
+ }
+ return ret;
+}