I have some code I have in the Arduino environment that requires x (in increments of 8) boolean values that are manipulatable during run time for some shift register code. So currently I am using a boolean array like so:
#define number_of_shiftRegisters 220 //num of 8 bit shift registers
#define numOfRegisterPins number_of_shiftRegisters * 8 //number of booleans needed
boolean registers[numOfRegisterPins]; //boolean array
But I was running out of RAM around 200 (1600 booleans) and didn't know why until I saw that, even though booleans are 1 bit, they are stored in 8 bits of data.
As I said before, the number of bools needed is always in an increment of 8, so I don't know if that could work to my advantage.
Is there a more memory efficient way to store 1000+ boolean values and still be able to reference them by index?
Or... At least more memory efficient that will not cost significantly more CPU time to set and iterate through?
I had thought about a char
array, and then bit masking each char to access the individual bits. But I didn't know if there was an easier way, or if this would take up considerably more CPU time.
Yes, you could easily use masking to get around that issue..
Every byte (unsigned char) will contain 8 boolean values, to get the i-th you can just use values & (1 << i)
in if tests, and it will work since if the correct bit is set, then result will be != to 0.
To set instead a bit just shift it and or to the value: values | (1 << i)
(in case of unset you have to AND it with 0).
Another solution could be to use a packed struct:
struct Bools
{
int b1 : 1;
int b2 : 1;
int b3 : 1;
... // up to b8
}
This should manage elements with direct access to the boolean value and allow you to define an union to manage them either as 8 single bit booleans value either as bytes.