0

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.

2

1 Answer 1

1

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);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks to your kindness. I had been just looking around to find direct way, but It doesn't fit for C++.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.