Many times I need to pass to functions or serialize an array of bits. If they are just a few (8-16 bits), I decide to use a standard array:
uint8_t my_short_array_of_bits[16]; void abits_set_bit(uint8_t *array, size_t size, uint8_t nbit); uint8_t abits_get_bit(uint8_t *arrray, size_t size, uint8_t nbit);
It sometimes occurs that the number of bits is much greater, maybe 100 or 200. If I developed on desktop/server machine, I would continue using array of uint8_t, but I'm developing on embedded platforms with limited resources.
So I started using uint32_t for 32 bits. It is very comfortable to test, set and clear a bit. I often need to set the N lowest bits or get the lowest bit set (__builtin_ctz).
For a recent project, I needed to increase the number of bits to 60, so the first idea is to use uint64_t. However I'm thinking to try to generalize for a bigger number of bits, because tomorrow someone will ask to increase the length again to 100 or 200.
Do you have some suggestions for this? Maybe in the same project I need to use an array of 100 bits and an array of 200 bits. I would prefer a typedef for both types, for example:
typedef uint8_t inputs_t[100]; uint8_t inputs_get_bit(inputs_t inputs, unsigned int nbit); void inputs_set_bit(...); void inputs_reset_bit(...); void inputs_toggle_bit(...); int inputs_ctz(inputs_t inputs); void inputs_set_low_bits(inputs_t inputs, unsigned int nbits);
typedef uint8_t outputs_t[200]; uint8_t outputs_get_bit(outputs_t inputs, unsigned int nbit); ...
Maybe I can create a .h file with preprocessor macro that will define static inline functions automatically for many types of arrays. Something similar to:
#define ABITS_TYPE_NAME inputs #define ABITS_LENGTH 100 #include "abits.h"
--- abits.h --- #define ABITS_TYPE CONCAT(ABITS_TYPE_NAME, _t) typedef uint8_t ABITS_TYPE[ABITS_LENGTH];
#define ABITS_GET_FUNC CONCAT(ABITS_TYPE_NAME, _get_bit) static inline uint8_t ABITS_GET_FUNC(ABITS_TYPE ABITS_TYPE_NAME, unsigned int nbits) { ... }
...
--- end of abits.h ---
I know I can try to write this .h file, but maybe there are some public domain code ready-to-use.