379_demos/lab9/bitwise.c

64 lines
1.3 KiB
C
Raw Normal View History

2024-11-18 18:00:36 -07:00
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h> // This gives us sized types
#include <stdbool.h>
#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++) {
2024-11-18 19:15:31 -07:00
printf("%02x", inodes[i]);
2024-11-18 18:00:36 -07:00
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");
fwrite(inodes, sizeof(uint8_t), NB_NODES, f);
fclose(f);
free(inodes);
}