Q:

Allocate n bytes for x bits

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!

A:

Assuming you want to initialize your bit-field to zero, calloc() might be preferable to malloc(); you probably also should use an unsigned type to avoid signed shifts when twiddling bits.
#include <limits.h>

const size_t BITS_PER_BLOCK = sizeof (long long) * CHAR_BIT;
size_t count = bits / BITS_PER_BLOCK + !!(bits % BITS_PER_BLOCK);
unsigned long long *blocks = calloc(count, sizeof *blocks);

The !! is a somewhat hackish way to convert non-zero values to 1, which is common in C and used here to allocate an additional block if the number of bits is not divisible by BITS_PER_BLOCK.
You could also get the required number of blocks (as - among others - Lars pointed out in the comments to another answer) via
size_t count = (bits + BITS_PER_BLOCK - 1) / BITS_PER_BLOCK;

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.

