Home >Backend Development >C++ >How to Efficiently Convert Between a Byte and Eight Boolean Values?

How to Efficiently Convert Between a Byte and Eight Boolean Values?

Linda Hamilton
Linda HamiltonOriginal
2024-12-12 11:38:08472browse

How to Efficiently Convert Between a Byte and Eight Boolean Values?

Creating a Byte from Boolean Values and Vice Versa

Problem:

You have eight Boolean variables and desire to merge them into a single byte. Conversely, you aim to decode a byte into eight distinct Boolean values.

Solution:

Hard Way:

unsigned char ToByte(bool b[8])
{
    unsigned char c = 0;
    for (int i = 0; i < 8; ++i)
        if (b[i])
            c |= 1 << i;
    return c;
}

void FromByte(unsigned char c, bool b[8])
{
    for (int i = 0; i < 8; ++i)
        b[i] = (c & (1 << i)) != 0;
}

Cool Way:

struct Bits
{
    unsigned b0 : 1, b1 : 1, b2 : 1, b3 : 1, b4 : 1, b5 : 1, b6 : 1, b7 : 1;
};

union CBits
{
    Bits bits;
    unsigned char byte;
};

Assign to one union member and read from another. Note that the order of bits in Bits is implementation-defined.

Caution:

Using unions in this manner is well-defined in ISO C99 and supported by some C compilers, but it is Undefined Behaviour in ISO C . Use memcpy or std::bit_cast for portable type-punning in C 20.

The above is the detailed content of How to Efficiently Convert Between a Byte and Eight Boolean Values?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn