That won't work either. On an 8-bit processor, bitfields that don't fit in the byte end up in another byte, so three :5 fields ends up taking 3 bytes on an 8-bit processor.
Here's a way around it, and in C++ you can encapsulate it in a class so it's transparent to the rest of the code. What I did was split the 2nd 5-bit field (the "green" one I named G) into 3 bits and 2 so that the first 3 bits fit in the 1st byte and the remaining 2 in a 2nd byte. Then the access functions split and combine the field and gets/sets its value.
If you want to access the three values as an array, create get and set functions for that as well:
Here's a way around it, and in C++ you can encapsulate it in a class so it's transparent to the rest of the code. What I did was split the 2nd 5-bit field (the "green" one I named G) into 3 bits and 2 so that the first 3 bits fit in the 1st byte and the remaining 2 in a 2nd byte. Then the access functions split and combine the field and gets/sets its value.
Code:
// Class stores 3 5-bit values and a boolean into 16 bits (2 bytes).
class RGBValue {
private:
unsigned pBCR :5; // Red (5-bits)
unsigned pBCG1 :3; // Green (upper 3-bits, shares byte with Red)
unsigned pBCG2 :2; // Green (bottom 2-bits, shares byte with Blue and Pressed)
unsigned pBCB :5; // Blue (5-bits)
unsigned pPressed :1; // Pressed flag (1 bit)
public:
//Access functions declarations
unsigned char getR(void);
unsigned char getG(void);
unsigned char getB(void);
bool getPressed(void);
void setR(unsigned char);
void setG(unsigned char);
void setB(unsigned char);
void setPressed(bool);
};
// Access functions implementation
unsigned char RGBValue::getR(void) {
return pBCR;
}
unsigned char RGBValue::getG(void) {
return pBCG1 << 2 | pBCG2;
}
unsigned char RGBValue::getB(void) {
return pBCB;
}
bool RGBValue::getPressed(void) {
return pPressed;
}
void RGBValue::setR(unsigned char Value) {
pBCR = Value;
}
void RGBValue::setG(unsigned char Value) {
pBCG1 = (Value >> 2) & 0x07;
pBCG2 = (Value & 0x03);
}
void RGBValue::setB(unsigned char Value) {
pBCB = Value;
}
void RGBValue::setPressed(bool Value) {
pPressed = Value;
}
If you want to access the three values as an array, create get and set functions for that as well:
Code:
unsigned char RGBValue::getColor(unsigned char index) {
switch(index) {
case 0:
return getR();
case 1:
return getG();
case 2:
return getB();
default:
return 0;
}
void RGBValue::setColor(unsigned char index, unsigned char value) {
switch(index) {
case 0:
setR(value);
break;
case 1:
setR(value);
break;
case 2:
setR(value);
break;
}
Last edited: