Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertical bitwise COUNT (sum of ones on the same position)

Is there any efficient way to do COUNT of ones on the same position in many variables? The count function should fill array with sum of ones in corresponding bit number. For example we have following three variables (I use 8-bit variables to make it simple):

uint8_t a = 0xF;  // 0000 1111
uint8_t b = 0x3C; // 0011 1100
uint8_t c = 0xF0; // 1111 0000

int result[8];

// some operations ...

count << result[0] << result[1] << .... // prints 1122 2211

I found many solutions for summing the ones in whole single variable, but not for the above problem.

like image 619
nosbor Avatar asked Sep 25 '22 04:09

nosbor


1 Answers

This little code does exactly what you want. You can easily expand it to support N variables through a little lookup array. Notice the use of the double not operation. It is to drag the output to either be 0 or 1.

#include <iostream>

using namespace std;

int main() {
    uint8_t a = 0xF;  // 0000 1111
    uint8_t b = 0x3C; // 0011 1100
    uint8_t c = 0xF0; // 1111 0000

    unsigned result[8];
    for(int i = 0; i < 8; ++i) {
        unsigned mask = 1 << i;
        result[i] = !!(a & mask) + !!(b & mask) + !!(c & mask);
    }

    for(int i = 0; i < 8; ++i)
        cout << result[i];
}
like image 195
SenselessCoder Avatar answered Dec 06 '22 07:12

SenselessCoder