S. R. Colledge
S. R. Colledge

Reputation: 111

Convert an array into a byte value in C++

For some context, I am using an program for the Arduino that uses byte formatted values like this: B10101010 and I am attempting to create a function that takes the first 8 values of an array like this [1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1] and converts it to the byte format shown above. My question is what is the simplest way to do this in C++? I hope the phrasing of the question makes sense. This is the format of the function that I want to enter the code into:

void bit_write (byte pins[]) {

}

Upvotes: 0

Views: 121

Answers (1)

Nikita  Sergeev
Nikita Sergeev

Reputation: 11

I think your function should have a signature like this: char bit_write( char pins[8] ) so you are going to convert a char array size of 8 to a single char (char has the same bitlength as std::byte but doesn't require c++17 to compile). Second, to fill a resulted char you could use bitwise operators, so it may look like this:

std::byte bit_write( const char pins[8] )
{
    short result = 0;
    for( unsigned i = 0; i < 8; ++i )
    {
        result |= (pins[i] < i);
    }

    return result;
}

Also note that the snippet below works if you use little-endian order of bytes, so pins array like [0, 1, 0, 1, 0, 1, 0, 1] will be B10101010.

Upvotes: 1

Related Questions