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::shared_ptr - 循环引用问题 阅读3852次,点赞0次
- C++ - 判断本机文件是否存在的方式总结 阅读4134次,点赞0次
- C++ - 使用标准库实现事件和委托,信号和槽机制 阅读181次,点赞0次
- C++ - Windows和Linux系统下获取当前可执行程序的绝对路径 阅读1446次,点赞0次
- C++ - 最简单的将文本文件的内容一次性读取到std::string的方法 阅读4245次,点赞4次
- C++11/std::thread - 线程的基本用法 阅读3083次,点赞0次
- C++ - linux编译C++代码出现error: use of deleted function std::atomic
::atomic(const std::atomic 阅读2002次,点赞0次&) - C++11 - 使用std::thread,std::shared_future,std::promise并行化/多线程化for循环,提升处理速度 阅读1307次,点赞0次
- C++ - 控制台程序在控制台窗口可变参数格式化带颜色输出日志信息 阅读2890次,点赞0次
- C++11/std::condition_variable - 生产者消费者模型 阅读2618次,点赞0次
全站随机文章推荐
- 资源分享 - OpenGL编程指南(原书第9版)- OpenGL红宝书高清带书签PDF下载 阅读11382次,点赞4次
- 资源分享 - Artificial Intelligence for Games , First Edition 英文高清PDF下载 阅读804次,点赞0次
- Pac - 自定义Pac的编写和语法规则 阅读4967次,点赞0次
- C++11/std::shared_ptr - 循环引用问题 阅读3852次,点赞0次
- C++11 - std::chrono - 使用std::chrono::duration_cast进行时间转换,hours/minutes/seconds/milliseconds/microseconds相互转换,以及自定义duration进行转换 阅读1942次,点赞0次
- C++11 - std::bind简要介绍以及可绑定函数的几种形式总结 阅读4288次,点赞4次
- 资源分享 - 深度学习实战(杨云杜飞 清华大学出版社)高清pdf下载 阅读2171次,点赞0次
- 资源分享 - 计算机动画算法与技术,Computer Animation - Algorithms and Techniques(Second Edition)中文版PDF下载 阅读989次,点赞0次
- 深度学习 - 图解Transformer,小白也能看懂的Transformer处理过程 阅读575次,点赞0次
- 左手坐标系与右手坐标系 阅读2915次,点赞0次
评论
164