Aaron Parrilla
Aaron Parrilla

Reputation: 542

Search for set/unset bit combination in value C++

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.

Upvotes: 2

Views: 131

Answers (3)

Jarod42
Jarod42

Reputation: 217348

Since C++14, you might write the function in intelligible way with binary representation:

bool isConditionVoid(std::uint8_t value) {
    bool Condition1 = ((value & 0b00'00'00'11) == 0b00'00'00'10);
    bool Condition2 = ((value & 0b00'00'11'00) == 0b00'00'10'00);
    bool Condition3 = ((value & 0b00'11'00'00) == 0b00'10'00'00);
    bool Condition4 = ((value & 0b11'00'00'00) == 0b10'00'00'00);

    return !Condition1 && !Condition2 && !Condition3 && !Condition4;
}

Upvotes: 1

The Long Nguyen
The Long Nguyen

Reputation: 92

First, in C++, int is shorted for signed int, and usually represented by 4 bytes, or 32 bits. So your function only work with the last 8 bits of input integer.

Second, 1<<n means 00 00 00 01 was shift by n bits to the left.

1<<8 means (01) 00 00 00 00
1<<7 means      10 00 00 00

Which mean all of your bit shift is deviated by 1 position to the left.

Third, the last if statement will return false when any of condition is false, which mean only 10101010 will return true.

Upvotes: 1

Pierre Abbat
Pierre Abbat

Reputation: 523

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.

Upvotes: 1

Related Questions