Task

Implement the function get_block_size

  • Write a function that takes a pointer to a block_header struct
  • The block_header struct contains a single size_t field, which encodes the block size and status bits
  • The block size is always a multiple of 16, so only the upper bits (all except the lowest 4 bits) represent the size. The lowest 4 bits are used for status flags and must be ignored when extracting the size

Function Signature

// Given a pointer to a block_header, return the size of the block (masking out status bits in the lower 4 bits).
size_t get_block_size(struct block_header* header);

Example

Encoded size_status valueBlock Size Returned
0x00000000000000410x40 (64)
0x00000000000001030x100 (256)
0x00000000000002070x200 (512)
0x00000000000008010x800 (2048)
0x000000000000100f0x1000 (4096)

Code

#include <stddef.h>
#include <stdio.h>
 
struct block_header {
    size_t size_status;
};
 
size_t get_block_size(struct block_header* block) {
    int dif = block->size_status % 16;
    if (dif == 0) {return block->size_status;}
    return block->size_status - dif;
}
 
int main(int argc, char** argv) {
    struct block_header a = {0x444};
    printf("before: %02lx, after:  %02lx\n", a.size_status, get_block_size(&a));
    return 0;
}