Vielleicht gefällt dir ja das Ergebnis meiner kleinen Fingerübung.
Relativ flexibel (16 oder weniger Bits für die Werte),
die Fehlerbehandlung (Index/Wert) kannst du ja bei Bedarf selbst hinzufügen.
class SamBuff {
public:
SamBuff(uint16_t bySize, byte biSize) {
mBuf = (byte*)malloc(byteSize);
bitSize = biSize;
if (mBuf != NULL) {
byteSize = bySize;
memset(mBuf, 0, byteSize);
bMask = 0;
for (byte i = 0; i < bitSize; i++) {
bMask <<= 1;
bMask |= 1;
}
} else {
byteSize = 0;
}
}
~SamBuff() {
free(mBuf);
}
uint16_t get(uint16_t index) {
uint16_t bitAddress = index * 8;
uint16_t byteAddress = bitAddress / bitSize;
byte bitOffset = bitAddress % bitSize;
uint16_t value = *((uint16_t*)(mBuf + byteAddress));
value >>= bitOffset;
return value & bMask;
}
void set(uint16_t index, uint16_t newVal) {
uint16_t bitAddress = index * 8;
uint16_t byteAddress = bitAddress / bitSize;
byte bitOffset = bitAddress % bitSize;
uint16_t value = *((uint16_t*)(mBuf + byteAddress));
value &= ~(bMask << bitOffset);
value |= (newVal << bitOffset);
*((uint16_t*)(mBuf + byteAddress)) = value;
}
uint16_t maxVal() {
return bMask;
}
private:
byte* mBuf;
uint16_t byteSize;
byte bitSize;
uint16_t bMask;
};
SamBuff test(128, 6);
void setup() {
Serial.begin(250000);
printSome(F("vorher "), 0, 16);
uint16_t tVal = test.maxVal();
for (byte i = 0; i < 16; i++) {
test.set(i, tVal--);
}
printSome(F("filled "), 0, 16);
test.set(4, test.maxVal());
test.set(6, test.maxVal());
printSome(F("set 4+6"), 0, 16);
}
void printSome(const __FlashStringHelper* mark, uint16_t from, uint16_t howMany) {
Serial.print(mark);
Serial.write(' ');
for (byte i = from; i < howMany; i++) {
Serial.print(test.get(i));
if (i != howMany - 1) {
Serial.print(F(", "));
}
}
Serial.println();
}
void loop() {}
vorher 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
filled 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48
set 4+6 63, 62, 61, 60, 63, 58, 63, 56, 55, 54, 53, 52, 51, 50, 49, 48