From 8d7cf17b397701b425fd4b4a54f699c8db2e5d8c Mon Sep 17 00:00:00 2001 From: Akemi Izuko Date: Mon, 18 Nov 2024 18:00:36 -0700 Subject: [PATCH] Lab9: bitwise example --- lab9/bitwise.c | 67 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 lab9/bitwise.c diff --git a/lab9/bitwise.c b/lab9/bitwise.c new file mode 100644 index 0000000..d0f5f76 --- /dev/null +++ b/lab9/bitwise.c @@ -0,0 +1,67 @@ +#include +#include +#include // This gives us sized types +#include + +#define NB_NODES 4 + +bool add_file(uint8_t* inodes, int file_size) { + // We only have 7 bits for the file size, so it can't be bigger + if (file_size > 0x7f || file_size < 0) { + return false; + } + + for (int i = 0; i < NB_NODES; i++) { + bool is_taken = (inodes[i] & 0x8) > 0; + + if (!is_taken) { + uint8_t size = file_size; + inodes[i] = size | 0x80; // Set highest bit + size + return true; + } + } + + return false; +} + +void printd_inodes(uint8_t* inodes) { + printf("Debug: "); + + for (int i = 0; i < NB_NODES; i++) { + printf("%x", inodes[i]); + + if (i == NB_NODES - 1) { + printf("\n"); + } else { + printf(" "); + } + } +} + +int main(void) { + uint8_t* inodes = calloc(NB_NODES, sizeof(uint8_t)); + + printd_inodes(inodes); + + add_file(inodes, 8); + printd_inodes(inodes); + + add_file(inodes, 12); + printd_inodes(inodes); + + add_file(inodes, 121); + printd_inodes(inodes); + + add_file(inodes, 127); + printd_inodes(inodes); + + FILE* f = fopen("bits.out", "wb"); + + char debug_msg[] = "Debug: "; + fwrite(debug_msg, sizeof(char), sizeof(debug_msg), f); + + fwrite(inodes, sizeof(uint8_t), NB_NODES, f); + fclose(f); + + free(inodes); +}