原创文章,欢迎转载。转载请注明:转载自 祥的博客
原文链接:https://cloud.tencent.com/developer/article/1596289
- 方法1:Union解析
- 方法2:指针强制类型转换
- 效果
进行UDP或者串口传输,都要将传输的数据转换为char类型数组进行传输,这样最简单的方式就是定义一个union共用体,但是有时候不需要那么麻烦,就需要用指针,强制类型转换,再解析。
下面代码,定义了一个Union共用体,两部分组成:
typedef unsigned int uint32;
union MyUnion
{
char buf[4];
uint32 number;
};
无疑,用MyUnion进行解析是最方便的。下面用第二种方法。
#include <iostream>
using namespace std;
typedef unsigned int uint32;
union MyUnion
{
char buf[4];
uint32 number;
};
bool reverseBuf2Num(const char* buf, float& number);//待实现
bool reverseBuf2Num(const char* buf, double& number);//待实现
bool reverseBuf2Num(const char* buf, int16& number);//待实现
bool reverseBuf2Num(const char* buf, int32& number);//待实现
bool reverseBuf2Num(const char* buf, uint16& number);//待实现
bool reverseBuf2Num(const char* buf, uint32& number)
{
if (NULL==buf)
{
number = 0;
return false;
}
uint32* pUint32 = (uint32*)buf;
number = *pUint32;
return true;
}
bool reverseNum2Buf(float number, char* buf);//待实现
bool reverseNum2Buf(double number, char* buf);//待实现
bool reverseNum2Buf(int16 number, char* buf);//待实现
bool reverseNum2Buf(int32 number, char* buf);//待实现
bool reverseNum2Buf(uint16 number, char* buf);//待实现
bool reverseNum2Buf(uint32 number, char* buf)
{
if (NULL == buf)
{
return false;
}
int i;
uint32* pUint32 = &number;
for (i = 0; i < 4; i++)
{
buf[i] = ((char*)pUint32)[i];
}
return true;
}
int main()
{
MyUnion t;
uint32 testN;
int i;
while (true)
{
cout << "Please input Uint32 Number: ";
cin >> t.number;//输入要解析的数值变量number
cout << "Buf of this Number:\n";
for (i = 0; i < 4;i++)
{
cout << (int)(t.buf[i]) << " ";//用Union查看在char[]中存放情况
}
cout << "\n\nBuf Reverse to Number:\n";
reverseBuf2Num(t.buf, testN);//用方法2进行解析,将char[]转换为uint32
cout << testN << endl;
cout << "================\nNumber Reverse to Buf:\n";
char tBuf[4];
reverseNum2Buf(testN, tBuf);//用方法2进行解析,将uint32转换为char[]
for (i = 0; i < 4; i++)
{
cout << (int)(tBuf[i]) << " ";
}
cout << "\n\n";
}
return 0;
}