Is there anyway to bool 2dimensional array to integer in C++?

57 views Asked by At

Guess there Is 2-dimensional bool array like this,

bool table[16][16] 

    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1  ...16[0][] ->1
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0  ...16[1][] ->2 
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1  ...16[2][] ->3
    0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1  ...16[3][] ->5
    0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1  ...16[4][] ->9
    ...
    0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,1  ...16[15][] ->41

And I know all of the bool value are aligned in a sequential address. Can I transform these array to int value using some type-cast function without using any arithmetic function? It seems like it is more natural way than calculating using pow function.

I used reinterpret_cast to solve it, But It doesn't work.

1

There are 1 answers

1
Sergey Kalinichenko On BEST ANSWER

C++ does not specify the way to store bool. Compilers may choose to store individual values as bytes or as any other type they like, so there is no no-op way of converting bool arrays to integers.

An array of std::bitset<16> could be used instead for a more compact representation. It also lets you get integral representation of the bits using to_ulong member function.

It seems like it is more natural way than calculating using pow function.

If this approach does not work for you, you can still do it with bit operations, not with power function:

int res = 0;
for (int b = 0 ; b != 16 ; b++) {
    if (table[row][b]) {
        res |= (1 << b);
    }
}