When making a bit array or also called a bit set in C what data type should I use? Should I use an array of int
? unsigned int
? size_t
? uint8_t
? uintmax_t
?
For me, using signed integer types is a no-no as noted by other answers here in SO about signed integer left and right shifts (I lost the link to the answer).
Now, should I use the smallest available unsigned integer or the biggest? Which one has the best performance?
Some of my thoughts: the majority of the bit arrays here in SO use an array of char
or uint8_t
, but I can't see how that would be better than using uintmax_t
(also because I haven't seen any arguments for why it is the way to go, hence this question). When making certain operations like union and intersection between two bit arrays the loop iterates fewer times when using a bigger unsigned integer.
Edit: upon seeing some answers I think some people got confused to what I'm asking. Sorry about that. What I'm trying to do is to make a bit array where each bit can be individually accessed or set to either 1 or 0. I know I could just use a bool array but that is not space efficient. You could say that nowadays we have RAMs that are big enough and the gain of bit arrays over boolean arrays is minimal but that's not the point here.
What I'm trying to know is, given a bit array where each bit can be modified or accessed by a bit_index
(which is different from the array's index) what data type should be my array?
int
). Using signed integers is a no-no, but with unsigned your're safe.char
is simpler as it hasCHAR_BIT
bits, usinguintmax_t
would need to countsizeof(uintmax_t) * CHAR_BIT
bits which is a bit longer to write. Alsouintmax_t
can generate unoptimal code. I guessint
would/should be the fastest and most memory efficient, but I would go forchar
for readability and scalability. You are asking a opinion based question about how to approach your implementation. - KamilCuktypedef unsigned char byte
it's a type in some libraries already anyway - Chris Rollins