379_demos/lab9/bitwise_with_names.c
2024-11-18 19:15:31 -07:00

76 lines
1.8 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h> // This gives us sized types
#include <stdbool.h>
#include <assert.h>
#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);
}