c++arraysraspberry-piboolean

Integer to binary stored in an array


TL:DR I have a 10-bit integer and want it as a binary number stored in an array.


Let's say I have an int from 0-1023 and I want that number converted to a 10-bit binary number that I will then put in an boolean array. Here is what I currently do.

void toBinary(bool *binary)
{
    string binaryStr = bitset<10>(myValue).to_string(); //to binary
    for (int i = 0; i < 10; i++) binary[i] = binaryStr[i] - '0';
}

Is there any better way then this? I will be doing some video processing with this and I'll be running it on a Pi, so I need my program to be as light and fast as possible.


Solution

  • I don't understand why do you convert the bitset to string. Just access it's elements directly.

    bitset<10> myBitset(myValue);
    for (int i = 0; i < 10; i++)
        binary[i] = myBitset[i];
    

    You could also go with bit shifting, that's the most low level way of doing this:

    int mask = 1; // binary 10000000 00000000 ...
    for (int i = 0, l = NUM_BITS; i < l; ++i) {
        // binary & operation does 
        // AND logic operation for all corresponging bit
        // so 0010&0011=0010
        binary[i] = myValue & mask;
        // move the bits in mask one to the right
        mask = mask>>1;
    }
    

    If you're going with bitset, I'd recommend that you keep the bitset instead of using bool* because in bitsets, every bit actually occupies one bit, whereas bool is eight bits large at least.

    Finally, here's some test code I made for that, you can use it to do benchmarks:

    #include <iostream>
    #include <bitset>
    #define NUM_BITS 10
    int main(int argc, char *argv[])
    {
        const int numBits = NUM_BITS;
        bool binary[numBits];
        const int myValue = 1;
    
        std::bitset<NUM_BITS> myBitset(myValue);
        //for (int i = 0; i < NUM_BITS; i++)
            //binary[i] = myBitset[i];
    
        for (int i = 0, l = NUM_BITS; i < l; ++i) {
            std::cout<< (binary[i]?'1':'0')<<" ";
        }
        std::cout<<"\n";
        int mask = 1; // binary 10000000 00000000 ...
        for (int i = 0, l = NUM_BITS; i < l; ++i) {
            // binary & operation does 
            // AND logic operation for all corresponging bit
            // so 0010&0011=0010
            binary[i] = myValue & mask;
            // move the bits in mask one to the right
            mask = mask>>1;
        }
    
        for (int i = 0, l = NUM_BITS; i < l; ++i) {
            std::cout<< (binary[i]?'1':'0')<<" ";
        }
    }