C++ – 字节数组byte[]或者unsigned char[]与int的相互转换
本文作者:StubbornHuang
版权声明:本文为站长原创文章,如果转载请注明原文链接!
原文标题:C++ – 字节数组byte[]或者unsigned char[]与int的相互转换
原文链接:https://www.stubbornhuang.com/960/
发布于:2020年11月10日 10:26:20
修改于:2022年03月11日 23:34:24

一个字节为8位二进制位
1 int转字节数组byte[]
C++中,字节数组byte通常用unsigned char表示,所以int转换为字节数组本质上是将int转换为unsigned char数组。int一般为4个字节,那么就为32位二进制位表示。
代码如下:
void IntToByte(int value, unsigned char* bytes)
{
size_t length = sizeof(int);
memset(bytes, 0, sizeof(unsigned char) * length);
bytes[0] = (unsigned char)(0xff & value);
bytes[1] = (unsigned char)((0xff00 & value) >> 8);
bytes[2] = (unsigned char)((0xff0000 & value) >> 16);
bytes[3] = (unsigned char)((0xff000000 & value) >> 24);
}
2 字节数组byte[]转int
代码如下:
int ByteToInt(unsigned char* byteArray)
{
int value = byteArray[0] & 0xFF;
value |= ((byteArray[1] << 8) & 0xFF00);
value |= ((byteArray[2] << 16) & 0xFF0000);
value |= ((byteArray[3] << 24) & 0xFF000000);
return value;
}
3 使用场景
例如在有些情况下的通信协议,举一个简单的栗子,在socket通信下,我们通常会想要知道本次接收的数据的长度有多大,那么这个时候就可以在要发送数据块的前面使用4个字节标志数据块的大小,而这时候就需要将int转换为字节数组。
4 使用示例
#include <iostream>
void IntToByte(int value, unsigned char* bytes)
{
size_t length = sizeof(int);
memset(bytes, 0, sizeof(unsigned char) * length);
bytes[0] = (unsigned char)(0xff & value);
bytes[1] = (unsigned char)((0xff00 & value) >> 8);
bytes[2] = (unsigned char)((0xff0000 & value) >> 16);
bytes[3] = (unsigned char)((0xff000000 & value) >> 24);
}
int ByteToInt(unsigned char* byteArray)
{
int value = byteArray[0] & 0xFF;
value |= ((byteArray[1] << 8) & 0xFF00);
value |= ((byteArray[2] << 16) & 0xFF0000);
value |= ((byteArray[3] << 24) & 0xFF000000);
return value;
}
int main()
{
unsigned char intByteArray[4];
int a = 10;
IntToByte(a, intByteArray);
std::cout << ByteToInt(intByteArray) << std::endl;
return 0;
}
当前分类随机文章推荐
- C++11/std::shared_ptr - 循环引用问题 阅读3999次,点赞0次
- C++ - std::unordered_map中使用结构体或者vector等复杂的数据结构作为Key值 阅读326次,点赞0次
- C++ - 将一维数组/二维数组/三维数组作为函数参数传递给函数 阅读1385次,点赞0次
- C++11/std::atomic - 原子变量(不加锁实现线程互斥) 阅读6119次,点赞2次
- C++ – UTF8编码下的全角字符转半角字符 阅读1572次,点赞0次
- C++ - 在某一天某个时间点定时执行任务,比如2022年9月19日晚上9点准点执行发送邮件函数 阅读307次,点赞0次
- C++STL容器 - std::map删除指定元素 阅读1684次,点赞0次
- C++11 - 父类与子类相互包含的时候该如何正确的使用智能指针,防止循环引用 阅读2445次,点赞0次
- GCC/GG++中编译优化选项-O -O0 -O1 -O2 -O3 -Os -Ofast -Og -Oz各自的区别和作用 阅读3080次,点赞2次
- C++11 - 构建一个符合实际应用要求的线程池 阅读1040次,点赞0次
全站随机文章推荐
- OpenCV - Mat与lplImage和CvMat的相互转换 阅读3601次,点赞0次
- OpenCV - 使用findContours()查找图片轮廓线,并将轮廓线坐标点输出 阅读4725次,点赞0次
- TensorRT - 计算模型推理时间 阅读80次,点赞1次
- ThreeJS - 设置透明背景模仿L2Dwidget.js看板娘渲染效果 阅读373次,点赞0次
- 书籍翻译 – Fundamentals of Computer Graphics, Fourth Edition,第7章 Viewing中文翻译 阅读2939次,点赞6次
- 深度学习 - 语音识别框架Wenet网络设计与实现 阅读243次,点赞0次
- 资源分享 - Computer Animation - Algorithms and Techniques (Third Edition) 英文高清PDF下载 阅读2206次,点赞1次
- 深度学习 - 为什么要初始化网络模型权重? 阅读338次,点赞0次
- CUDA 安装报错 could not create file "...\chrome_elf.dll" 阅读1621次,点赞0次
- C++ - Map中存储动态指针时正确释放内存 阅读3673次,点赞0次
评论
167