First, this can be a general algorithm for any language, but I’m learning C and if there is some C specific features, I’d like to know!
I’m writing a function that will allocate enough memory for a given number of bits; into a long long * variable. The number of bits cannot be < 1. I tested the algorithm :
int bits; // the function argument, checked for value > 0
size_t dataSize; // the value passed to the malloc function
for (bits = 1; bits<100; bits++) {
if (bits < sizeof(long long)) {
dataSize = 1;
} else {
dataSize = (bits + (sizeof(long long) - (bits % sizeof(long long)))) / sizeof(long long);
}
printf("%d = %d\n", bits, (int) dataSize);
}
It looks ok… but ugly 🙂
Any way to have a more elegant way to achieve this?
Thank you!
Assuming you want to initialize your bit-field to zero,
calloc()might be preferable tomalloc(); you probably also should use an unsigned type to avoid signed shifts when twiddling bits.The
!!is a somewhat hackish way to convert non-zero values to1, which is common in C and used here to allocate an additional block if the number of bits is not divisible byBITS_PER_BLOCK.You could also get the required number of blocks (as – among others – Lars pointed out in the comments to another answer) via
I find the former version more readable, but as the latter is also quite common – it’s a special case of a more general rounding algorithm using integer arithmetics – a C programmer should be comfortable with either choice.