c++ - 将 uint8 数组反序列化为 int64 失败但应该可以

标签 c++ serialization deserialization byte-shifting

我要通过 tcp 发送一个 int64 并需要对其进行序列化和反序列化。

首先我将它转换为 uin64。

我将它字节移位到一个 uint8 数组中。

然后我将数组字节移位为 uint64

最后将其转换回 int。

但它返回的值与我输入的不同... 我检查了十六进制值,但它们应该是正确的...

代码:

#include <math.h>
#include <string.h>
#include <iostream>
#include <iomanip>

//SER & D-SER int64
std::array<uint8_t, 8> int64ToBytes(int64_t val)
{
   uint64_t v = (uint64_t)val;
   std::array<uint8_t, 8> bytes;
   bytes[0] = (v&0xFF00000000000000)>>56;
   bytes[1] = (v&0x00FF000000000000)>>48;
   bytes[2] = (v&0x0000FF0000000000)>>40;
   bytes[3] = (v&0x000000FF00000000)>>32;
   bytes[4] = (v&0x00000000FF000000)>>24;
   bytes[5] = (v&0x0000000000FF0000)>>16;
   bytes[6] = (v&0x000000000000FF00)>>8;
   bytes[7] = (v&0x00000000000000FF);
   return bytes;
}

int64_t bytesToInt64(uint8_t bytes[8])
{
   uint64_t v = 0;
   v |= bytes[0]; v <<= 8;
   v |= bytes[1]; v <<= 8;
   v |= bytes[3]; v <<= 8;
   v |= bytes[4]; v <<= 8;
   v |= bytes[5]; v <<= 8;
   v |= bytes[6]; v <<= 8;
   v |= bytes[7]; v <<= 8;
   v |= bytes[8];
   return (int64_t)v;
}


int main() {
   uint8_t bytes[8] = {0};

   int64_t val = 1234567890;

   //Print value to be received on the other side
   std::cout << std::dec << "INPUT:  " << val << std::endl;

   //Serialize
   memcpy(&bytes, int64ToBytes(val).data(), 8);

   //Deserialize
   int64_t val2 = bytesToInt64(bytes);

   //print deserialized int64
   std::cout << std::dec << "RESULT: " << val2 << std::endl;
}

输出:

INPUT:  1234567890
RESULT: 316049379840

试了一天了,还是找不到问题

谢谢。

最佳答案

尝试使用 uint64_t htobe64(uint64_t host_64bits) 和 uint64_t be64toh(uint64_t big_endian_64bits) 函数分别从主机转换为大端(网络顺序)和从网络顺序转换为主机顺序。

您正在移动整个值。尝试类似的东西:

(bytes[0] << 56) | 
(bytes[1] << 48) |
...  (bytes[7])

没有第 9 个字节(即 byte[8])。

关于c++ - 将 uint8 数组反序列化为 int64 失败但应该可以,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55180710/

相关文章:

c# - 配置 .NET WCF UTF-8 反序列化器以修改/丢弃非最短格式字符而不是抛出异常?

c# - 如何干净地反序列化字符串值包含在同名对象中的 JSON

c++ - 为什么派生类没有vtable指针而是使用基类的vtable?

c++ - 有没有办法在 C++ 中并行循环遍历 vector 的所有元素?

c++ - 将类成员函数作为参数传递给全局函数

c++ - 在 Visual Studio 2010 中创建字节数组时出现堆栈溢出

c# - XML 序列化错误 - 类型 'ItemsElementName' 的选择标识符 'ItemsChoiceType[]' 的值无效或缺失

json - 使用 POST 请求将 WebApi 序列化为 Json

java - GSON 正确序列化枚举,但将其反序列化为字符串

c++ - 在 C++ 中加载数据的最快方法