Search code examples
c++bit-manipulationbitwise-operatorsuint32

C++ - Given multiple binary strings, produce binary string where n-th bit is set if in all given strings is n-th bit same


On input I am given multiple uint32_t numbers, which are in fact binary strings of length 32. I want to produce binary string ( a.k.a. another uint32_t number ) where n-th bit is set to 1 if n-th bit in every given string from input is same.


Here is simple example with 4 bit string ( just more simple instance of same problem ) :

input: 0011, 0101, 0110

output: 1000

because: first bit is same in every string on input, therfore first bit in output will be set to 1 and 2nd,3rd and 4th will be set to 0 because they have different values.


What is the best way to produce output from given input? I know that I need to use bitwise operators but I don't know which of them and in which order.

uint32_t getResult( const vector< uint32_t > & data ){
    //todo
}

Solution

  • You want the bits where all the source bits are 1 and the bits where all the source bits are 0. Just AND the source values and the NOT of the source values, then OR the results.

    uint32_t getResult( const vector< uint32_t > & data ){
        uint32_t bitsSet = ~0; 
        uint32_t bitsClear = ~0;
        for (uint32_t d : data) {
            bitsSet &= d;
            bitsClear &= ~d;
        }
        return bitsSet | bitsClear
    }