diff --git a/lab9/bitwise.c b/lab9/bitwise.c index d0f5f76..d368aa0 100644 --- a/lab9/bitwise.c +++ b/lab9/bitwise.c @@ -28,7 +28,7 @@ void printd_inodes(uint8_t* inodes) { printf("Debug: "); for (int i = 0; i < NB_NODES; i++) { - printf("%x", inodes[i]); + printf("%02x", inodes[i]); if (i == NB_NODES - 1) { printf("\n"); @@ -56,10 +56,6 @@ int main(void) { 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); diff --git a/lab9/bitwise_with_names.c b/lab9/bitwise_with_names.c new file mode 100644 index 0000000..c8effd2 --- /dev/null +++ b/lab9/bitwise_with_names.c @@ -0,0 +1,76 @@ +#include +#include +#include // This gives us sized types +#include +#include + +#define NB_NODES 4 + +bool add_file(uint64_t* inodes, int file_size, char name[7]) { + // 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] >> (7*8)) & 0x8) > 0; + + if (!is_taken) { + // Set highest bit + inodes[i] = ((uint64_t) file_size | 0x80) << (7*8); + + // Set name byte by byte + for (int ii = 0; ii < 7; ii++) { + inodes[i] |= (((uint64_t) name[ii]) & 0xff) << (ii*8); + } + return true; + } + } + + return false; +} + +void printd_inodes(uint64_t* inodes) { + printf("Debug with name: "); + + for (int i = 0; i < NB_NODES; i++) { + for (int ii = 0; ii < 7; ii++) { + // Get character out + printf("%c", (uint8_t) ((inodes[i] >> (ii*8)) & 0xff)); + } + + printf(" %02x", (uint8_t) (inodes[i] >> (7*8))); + + if (i == NB_NODES - 1) { + printf("\n"); + } else { + printf(" "); + } + } +} + +int main(void) { + // Use bottom 8 bits for file size (7 bits) and occupied indicator (1 bit) + // Use top 56 bits for 7 character name + uint64_t* inodes = calloc(NB_NODES, sizeof(uint64_t)); + + printd_inodes(inodes); + + add_file(inodes, 8, "one\0\0\0"); + printd_inodes(inodes); + + add_file(inodes, 12, "two\0\0\0"); + printd_inodes(inodes); + + assert(add_file(inodes, 121, "another")); + printd_inodes(inodes); + + add_file(inodes, 127, "four\0\0"); + printd_inodes(inodes); + + FILE* f = fopen("bits.out", "wb"); + fwrite(inodes, sizeof(uint64_t), NB_NODES, f); + fclose(f); + + free(inodes); +}