我正在尝试获取两个双精度(GPS 坐标)并通过 ZigBee API 将它们发送到另一个 ZigBee 接收器单元,但我不知道如何将双精度分解为字节数组,然后将它们重新组合成原始形式一旦他们被转移。
基本上,我需要将每个双精度转换为一个由八个原始字节组成的数组,然后获取该原始数据并再次重建双精度。
有任何想法吗?
您正在做的事情称为类型双关语。
使用联合:
union {
double d[2];
char b[sizeof(double) * 2];
};
或使用reinterpret_cast
:
char* b = reinterpret_cast<char*>(d);
这是一种相当不安全的方法:
double d = 0.123;
char *byteArray = (char*)&d;
// we now have our 8 bytes
double final = *((double*)byteArray);
std::cout << final; // or whatever
或者您可以使用 reinterpret_cast:
double d = 0.123;
char* byteArray = reinterpret_cast<char*>(&d);
// we now have our 8 bytes
double final = *reinterpret_cast<double*>(byteArray);
std::cout << final; // or whatever
通常双精度已经是八个字节。请通过比较 sizeof(double) 和 sizeof(char) 在您的操作系统上验证这一点。C++ 没有声明一个byte,通常它意味着char
如果确实如此。
double x[2] = { 1.0 , 2.0};
double* pToDouble = &x[0];
char* bytes = reinterpret_cast<char*>(pToDouble);
现在字节是您需要发送到 ZigBee 的内容