【问题标题】:Each deserialized 64 bit integer number should be converted to bit wise equivalent 64 bit floating number每个反序列化的 64 位整数应转换为按位等效的 64 位浮点数
【发布时间】:2017-07-22 05:06:53
【问题描述】:

我在我引用的文件中有上述声明。预期产量翻倍。我找不到与我的问题相关的任何内容。 我找到了这个 Passing a structure through Sockets in C 但不知道它是否相关。 我没有读到那个 int64 值。我从其他过程中得到它,这就是它的设计方式。

有人对整数的序列化和反序列化有任何理论吗?

【问题讨论】:

  • 为什么不直接将数据读入double
  • std::memcpy 将为您完成。 int64 和 float 的联合是 UB,
  • 感谢 Nathan 的更新。我没有读那个。我从其他过程中得到它,这就是它的设计方式。
  • @RichardCritten void * comp = &(x_double);双分量 = (*(F64 *)comp);我想这和它没用的一样
  • 也是UB。 memcpy 现在是在不同类型之间复制数据的唯一标准定义方式(iirc 很少有使用 char / unsigned char 的边缘情况)。

标签: c++ serialization floating-point deserialization bitwise-operators


【解决方案1】:

在 c++ 中,确切地定义了一种将一种类型按位复制到另一种类型的方法 - memcpy

template<class Out, class In, std::enable_if_t<(sizeof(In) == sizeof(Out))>* = nullptr>
Out mangle(const In& in)
{
    Out result;
    std::memcpy(std::addressof(result), std::addressof(in), sizeof(Out));
    return result;
}


int main()
{
    double a = 1.1;
    auto b = mangle<std::uint64_t>(a);
    auto c = mangle<double>(b);

    std::cout << a << " " << std::hex << b << " " << c << std::endl;
}

示例输出:

1.1 3ff199999999999a 1.1

【讨论】:

  • void * comp = &(x_double);双分量 = (*(F64 *)comp);我得到了相同的答案,但不是正确的。但感谢您的帮助
  • 您可能会得到相同的答案,但是标准未定义使用 c 样式转换时的行为
【解决方案2】:

如何读取该 64 位数字并使用 reinterpret_cast 将其转换为按位等效的浮点数。

int64_t a = 121314;
double b = *reinterpret_cast<double*>(&a);
int64_t c = *reinterpret_cast<int64_t*>(&b);
assert(a==c);

【讨论】:

  • 谢谢,但它不会生成错误 C2440: 'reinterpret_cast': cannot convert from 'int64_t' to 'double'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-22
  • 1970-01-01
  • 2012-08-03
  • 2011-02-10
  • 1970-01-01
  • 2019-08-17
  • 1970-01-01
相关资源
最近更新 更多