0

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[]) {

}
3
  • @molbdnilo you're right. Let me change that Commented Mar 19, 2020 at 7:51
  • Your function signature doesn't work. First, you need another parameter for the length of the array, otherwise you won't know how long it is. Second you need to return the result. What is the return type supposed to be? What should happen if the passed array is larger than what the type can hold? Commented Mar 19, 2020 at 8:21
  • @walnut the return type is suppose to be in byte (B10101010) format. I think the size of the array can be found just by using the sizeof command. And by the way, the array passed in will always be that same size. Sorry that I didn't clarify this in the post Commented Mar 19, 2020 at 15:24

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Sergeev when I test this code out it gives me this error exit status 1 'byte' in namespace 'std' does not name a type and error: expected primary-expression before 'const'. Do I need to include some libraries?
Instead of std::byte please use char or short, they have the same width.

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.