C++ byteToInt,intToByte

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/wubw0585/article/details/87827898

以下均为小端cpu

1字节 uint8_t
2字节 uint16_t
4字节 uint32_t
8字节 uint64_t

(1) bytetoInt

这个为大端
struct test
{
char pCount[4];
};
test st;
//将char[4]转化成int,char[3]为低8位
int count = (st.pCount[0]<<24) | (st.pCount[1]<<16) | (st.pCount[2]<<8) | st.pCount[3];

以下均为小端
//byte数组长度为4, bytes[3]为高8位
uint32_t bytesToInt(uint8_t* bytes)
{
uint32_t tmp = 0x00;
tmp = (tmp | bytes[3]) << 8;
tmp = (tmp | bytes[2]) << 8;
tmp = (tmp | bytes[1]) << 8;
tmp = (tmp | bytes[0]) ;
return tmp;
}

// byte数组长度为4, bytes[3]为高8位
uint32_t bytes2Int(uint8_t* bytes)
{
uint32_t value=0;
value = ((bytes[3] & 0xff)<<24)|
((bytes[2] & 0xff)<<16)|
((bytes[1] & 0xff)<<8) |
( bytes[0] & 0xff);

return value;

}

例子:
uint8_t ss[4] = {1,1,0,0};
int val = bytes2Int(ss);
qDebug()<<"========== val : "<<val;

打印:
========== val : 257

(2) intToBytes
uint8_t* int2Bytes( uint32_t value )
{
uint8_t* src = new uint8_t[4];
src[3] = (uint8_t) ((value>>24) & 0xFF);
src[2] = (uint8_t) ((value>>16) & 0xFF);
src[1] = (uint8_t) ((value>>8) & 0xFF);
src[0] = (uint8_t) (value & 0xFF);
return src;
}

例子:
uint8_t* arr = int2Bytes(257);
qDebug()<<"========== arr[0] : “<<arr[0]
<<”\n========== arr[1] : “<<arr[1]
<<”\n========== arr[2] : “<<arr[2]
<<”\n========== arr[3] : "<<arr[3];

打印:
========== arr[0] : 1
========== arr[1] : 1
========== arr[2] : 0
========== arr[3] : 0

展开阅读全文

没有更多推荐了,返回首页