I need to write a series of unsigned integers to a file, each one being no greater than a limit n
determined at runtime. To save space, I want to pack them in as little bytes as possible. However, I've no idea how to compute the minimum number of bytes necessary to hold them, so I only have the following, ugly solution:
int get_needed_bytes(uint32_t n) {
if (n < 256) return 1;
else if (n < 65536) return 2;
else if (n < 16777216) return 3;
return 4;
}
Is there a better way to achieve the same purpose?