TIL: Deconstruct C types of unknown size to byte array

2022-06-01 00:00:00 +0000 UTC

When working with types like int, long, or time_t in C you cannot write an unrolled conversion into a byte array and expect portability. Instead you have to use the sizeof operator to produce a loop like the following:

uint8_t* split_timet_bytewise(uint8_t* dest, time_t src, size_t index) {
    if (!dest) return 0;


    size_t tsz = sizeof(time_t);
    uint8_t* ptr = dest + index;


    for (size_t i = tsz-1; i < tsz; --i) {
        time_t mask = 0xff << (i * 8);
        time_t offset = 8 * i;
        ptr[index+i] = (src & mask) >> offset;
    }


    return dest;
}

This still may run into issues of endianness across platforms but allows portability with respect to the size of time_t.

Tags: til c