设定bool型字节长度为1。

1 bool转字节数组

bool型转字节数组byte[]或者unsigned char[]

void BoolTobytes(bool data, unsigned char bytes[])
{
    if (data) 
    {
        bytes[0] = (unsigned char)(0x01 & 1);
    }
    else {
        bytes[0] = (unsigned char)(0x01 & 0);
    }
}

2 字节数组转bool

字节数组byte[]或者unsigned char[]转bool型

bool BytesToBool(unsigned char bytes[])
{
    return (bytes[0] & 0x01) == 1 ? true : false;
}

3 使用示例

#include <iostream>

bool BytesToBool(unsigned char bytes[])
{
    return (bytes[0] & 0x01) == 1 ? true : false;
}

void BoolTobytes(bool data, unsigned char bytes[])
{
    if (data) 
    {
        bytes[0] = (unsigned char)(0x01 & 1);
    }
    else {
        bytes[0] = (unsigned char)(0x01 & 0);
    }
}


int main()
{
    unsigned char boolByteArray[1];
    bool a = true;
    BoolTobytes(a, boolByteArray);

    std::cout << BytesToBool(boolByteArray) << std::endl;

    return 0;
}