BitArray.h

#ifndef __BITARRAY_H__

#define __BITARRAY_H__

#include <Arduino.h>

// The BitArray class stores bits in one or more bytes.

// This class can be used for maintaining boolean flags in a memory effecient way.

// A normal boolean takes up a whole byte.

// T is an (unsigned) integer datatype.

template<typename T>

class BitArray

{

public:

BitArray(T initialValues)

{

_bits = initialValues;

}

bool Set(byte bitIndex, bool value)

{

if (bitIndex > getMaxBits()) return false;

T mask = 1 << bitIndex;

// clear bit

_bits &= ~mask;

if (value)

{

// set bit

_bits |= mask;

}

return true;

}

bool IsTrue(byte bitIndex)

{

if (bitIndex > getMaxBits()) return false;

T mask = 1 << bitIndex;

return ((_bits & mask) > 0);

}

bool IsFalse(byte bitIndex)

{

if (bitIndex > getMaxBits()) return false;

T mask = 1 << bitIndex;

return ((_bits & mask) == 0);

}

byte getMaxBits()

{

return (sizeof(T) * 8);

}

bool operator[] (byte bitIndex)

{

return IsTrue(bitIndex);

}

operator T()

{

return _bits;

}

private:

T _bits;

};

#endif //__BITARRAY_H__

usage:

#include <HardwareSerial.h>

#include "BitArray.h"

BitArray<byte> bits(0);

void setup()

{

Serial.begin(115200);

bits.Set(0, false);

bits.Set(1, false);

bits.Set(2, true);

bits.Set(3, false);

bits.Set(4, false);

bits.Set(5, false);

bits.Set(6, true);

bits.Set(7, true);

}

void loop()

{

Serial.print(bits.getMaxBits());

Serial.println(" bits");

Serial.print("value = ");

Serial.println(bits);

for (int i = 0; i < bits.getMaxBits(); i++)

{

Serial.print(i);

Serial.print(" = ");

Serial.println(bits.IsTrue(i) ? "true" : "false");

}

delay(2000);

}