It's my first time working with C++ and I'm tryin to identify if the bits of a given int fall into a specific category:
For each int passed to the function, we implement the rule that every 2 bits represent a singular value within the message, and if that message's value is 2 (10 binary) then we need to return a boolean with false. Examples: (In the column binary representation I separate each 2 bits so its more visible)
Given value | Binary representation | condition met | Returns |
---|---|---|---|
0 | 00 00 00 00 | None | true (no condition met) |
128 | 10 00 00 00 | 1st | false |
32 | (00) 10 00 00 | 2nd | false |
8 | (00 00) 10 00 | 3rd | false |
2 | (00 00 00) 10 | 4th | false |
217 | 11 01 10 01 | 3rd | false |
153 | 10 01 10 01 | 1st & 3rd | false |
I've found about this and this and tried making a simple function, but it's not working as intended.
bool isConditionVoid(int value) {
bool Condition1 = (value &(1<<8)) && !(value&(1<<7));
bool Condition2 = (value &(1<<6)) && !(value&(1<<5));
bool Condition3 = (value &(1<<4)) && !(value&(1<<3));
bool Condition4 = (value &(1<<2)) && !(value&(1<<1));
if (!Condition1 || !Condition2 || !Condition3 || !Condition4)
return false;
else
return true;
}
Knowing which condition failed could be a plus, but it's not necessary. Any help would be greatly appreciated.
unsigned int condition=((value&0xaaaaaaaa)>>1)&((~value)&0x55555555);
This computes a number which has a bit set for each message that is 2. If for example value=0b11011001
, value&0xaaaaaaaa
is 0b10001000
, shifting right produces 0b01000100
~value
is 0b11111111111111111111111100100110
, anding with 0x55555555
produces 0b01010101010101010101010100000100
, and the final and produces 0b100
, showing that condition 3 is met.