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

设定long型长度为4字节。
1 long转字节数组
long型转字节数组byte[]或者unsigned char[]
void LongToBytes(long value, unsigned char* bytes)
{
size_t length = sizeof(long);
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 字节数组转long
字节数组byte[]或者unsigned char[]转long型
long BytesToLong(unsigned char* bytes)
{
long value = bytes[0] & 0xFF;
value |= ((bytes[1] << 8) & 0xFF00);
value |= ((bytes[2] << 16) & 0xFF0000);
value |= ((bytes[3] << 24) & 0xFF000000);
return value;
}
3 使用示例
#include <iostream>
void LongToBytes(long value, unsigned char* bytes)
{
size_t length = sizeof(long);
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);
}
long BytesToLong(unsigned char* bytes)
{
long value = bytes[0] & 0xFF;
value |= ((bytes[1] << 8) & 0xFF00);
value |= ((bytes[2] << 16) & 0xFF0000);
value |= ((bytes[3] << 24) & 0xFF000000);
return value;
}
int main()
{
unsigned char longByteArray[4];
long a = 10;
LongToBytes(a, longByteArray);
std::cout << BytesToLong(longByteArray) << std::endl;
return 0;
}
当前分类随机文章推荐
- C++ - std::map正向遍历与反向遍历的几种方式 阅读4148次,点赞3次
- C++ - 线程安全的std::cout 阅读1897次,点赞0次
- C++ - vector存储动态指针时正确释放内存 阅读5579次,点赞0次
- C++ - Windows/Linux生成uuid(通用唯一识别码) 阅读1488次,点赞2次
- C++ - 将Unicode std::wstring字符串转换为Unicode std::string转义字符,类似于\uxxxx的形式 阅读1422次,点赞0次
- Windows - 使用类的成员函数作为Win32窗口消息回调处理函数WindowProc 阅读913次,点赞0次
- C++STL容器 - std::map容器修改、元素操作总结 clear,insert,emplace,erase,swap,merge,extract,insert_or_assign等 阅读1371次,点赞0次
- C++ - 使用std::chrono获取当前秒级/毫秒级/微秒级/纳秒级时间戳 阅读3002次,点赞0次
- C++ - int转string方法总结 阅读6224次,点赞0次
- C++ - 将std::vector中的数值拷贝到数组中 阅读2139次,点赞1次
全站随机文章推荐
- 工具推荐 - 一些好用的DNS服务器 阅读742次,点赞0次
- 资源下载 - OpenGL着色语言OpenGL橙宝书PDF中文版下载 阅读7266次,点赞5次
- Numpy - 保存和加载numpy数组、字典、列表数据 阅读599次,点赞0次
- 资源分享 - OpenGL Insights 英文高清PDF下载 阅读2551次,点赞0次
- 资源分享 - OpenGL 4.0 Shading Language Cookbook (Third Edition) 英文高清PDF下载 阅读2797次,点赞0次
- C++ - 对字符串和图片进行base64编解码 阅读131次,点赞0次
- WordPress - 插件WP Editor.md 在网站更换为https后无法正确加载 阅读3941次,点赞0次
- 资源分享 - The Algorithms and Principles of Non-photorealistic Graphics - Artistic Rendering and Cartoon Animation 英文高清PDF下载 阅读1330次,点赞0次
- 资源分享 - GPU Gems中文译文版GPU 精粹(1-3) 高清PDF下载 阅读8130次,点赞1次
- 资源分享 - Computational Geometry - Algorithms and Applications, First Edition 英文高清PDF下载 阅读1598次,点赞0次
评论
167