C++ – 字节数组byte[]或者unsigned char[]与long的相互转换
设定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;
}
本文作者:StubbornHuang
版权声明:本文为站长原创文章,如果转载请注明原文链接!
原文标题:C++ – 字节数组byte[]或者unsigned char[]与long的相互转换
原文链接:https://www.stubbornhuang.com/2026/
发布于:2022年03月11日 23:40:53
修改于:2023年06月26日 20:29:20
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
评论
50