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++11 - 使用std::thread::join()/std::thread::detach()方法需要注意的点 阅读2901次,点赞0次
- C++ - 使用模板和智能指针构建一个双向链表工具类 阅读965次,点赞0次
- C++ - 将Unicode std::wstring字符串转换为Unicode std::string转义字符,类似于\uxxxx的形式 阅读1611次,点赞0次
- C++11/std::shared_ptr - 循环引用问题 阅读4166次,点赞0次
- C++ – Unicode编码下的全角字符转半角字符 阅读2067次,点赞0次
- C++ - 左值和右值,右值引用与移动语义的概念与理解 阅读368次,点赞1次
- C++11 - 构建一个符合实际应用要求的线程池 阅读1189次,点赞0次
- CMake - 设置Debug或者Release编译模式 阅读2876次,点赞0次
- C++11 - 基于无锁队列的单生产者单消费者模型 阅读6005次,点赞1次
- C++11 - 封装std::thread,增加子线程启动、暂停、唤起、停止功能 阅读4834次,点赞7次
全站随机文章推荐
- 深度学习 - CTC解码算法详解 阅读878次,点赞0次
- 资源分享 – OpenGL SuperBible – Comprehensive Tutorial and Reference (Seventh Edition) OpenGL蓝宝书第7版英文高清PDF下载 阅读2581次,点赞2次
- 资源下载 - Go语言实战WilliamKennedy高清带书签PDF下载 阅读2767次,点赞0次
- 左手坐标系与右手坐标系 阅读3224次,点赞0次
- 资源分享 - Ray Tracing - The Rest of Your Life英文高清PDF下载 阅读2447次,点赞0次
- 资源分享 - Digital Image Processing , Second Edition 英文高清PDF下载 阅读2107次,点赞0次
- Modern OpenGL从零开始 - 在Visual Studio中配置OpenGL开发环境 阅读2517次,点赞0次
- FFmpge - Ubuntu编译FFmpeg出现WARNING: pkg-config not found, library detection may fail警告 阅读4385次,点赞0次
- C++ - return this和return *this的含义和区别 阅读412次,点赞0次
- C++ - 获取当前进程内存使用情况 阅读9104次,点赞10次
评论
169