C++ – 字节数组byte[]或者unsigned char[]与bool的相互转换
本文作者:StubbornHuang
版权声明:本文为站长原创文章,如果转载请注明原文链接!
原文标题:C++ – 字节数组byte[]或者unsigned char[]与bool的相互转换
原文链接:https://www.stubbornhuang.com/2037/
发布于:2022年03月16日 22:22:49
修改于:2022年03月14日 22:26:54

设定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;
}
当前分类随机文章推荐
- C++ - 将Unicode std::wstring字符串转换为Unicode std::string转义字符,类似于\uxxxx的形式 阅读390次,点赞0次
- C++11 - 使用std::thread在类内部以成员函数作为多线程函数执行异步操作 阅读720次,点赞0次
- C++ – 字节数组byte[]或者unsigned char[]与long long的相互转换 阅读197次,点赞0次
- C++ - 最简单的将文本文件的内容一次性读取到std::string的方法 阅读2436次,点赞2次
- C++ - 将一维数组/二维数组/三维数组作为函数参数传递给函数 阅读349次,点赞0次
- C++STL容器 - std::map删除指定元素 阅读307次,点赞0次
- GCC/GG++中编译优化选项-O -O0 -O1 -O2 -O3 -Os -Ofast -Og -Oz各自的区别和作用 阅读140次,点赞0次
- 计算几何 - C++计算两个二维向量的夹角 阅读1530次,点赞3次
- C++ - 求解std::vector
中topk数值以及topk数值对应的索引 阅读436次,点赞0次 - C++ - 字节数组byte[]或者unsigned char[]与long的相互转换 阅读146次,点赞0次
全站随机文章推荐
- FFmpeg - 关于ffmpeg avcodec_open2函数失败的问题 阅读2433次,点赞0次
- C++ – 字节数组byte[]或者unsigned char[]与short的相互转换 阅读179次,点赞0次
- Pytorch – 使用torch.matmul()替换torch.einsum('bhxyd,md->bhxym',(a,b))算子模式 阅读95次,点赞0次
- 资源分享 - 图解机器学习(日 杉山将著 许永伟译)PDF下载 阅读2255次,点赞0次
- 资源分享 - Digital Lighting & Rendering , Third Edition 英文高清PDF下载 阅读310次,点赞0次
- C++ 11 - final关键字简要介绍 阅读1280次,点赞0次
- 资源分享 - Image Content Retargeting - Maintaining Color, Tone, and Spatial Consistency 英文高清PDF下载 阅读536次,点赞0次
- Marching Cube(C++ OpenGl代码)读取医学三维图像*.raw进行三维重建 阅读5557次,点赞3次
- 资源分享 - Mathematics for 3D Game Programming and Computer Graphics, Second Edition 英文高清PDF下载 阅读1729次,点赞0次
- C++11 - override关键字简要介绍 阅读1328次,点赞0次
评论
144