【问题标题】:'cout' displays integer as hex'cout' 将整数显示为十六进制
【发布时间】:2019-12-09 08:53:33
【问题描述】:

我使用 memcpy 将多个字节合并为一个整数。该代码似乎有效,并且值可以毫无问题地用于进一步计算。但是如果我用 cout 显示结果,值显示为十六进制:

代码:

int readByNameInt(const char handleName[], std::ostream& out, long port, const AmsAddr& server)
{
    uint32_t bytesRead;

    out << __FUNCTION__ << "():\n";
    const uint32_t handle = getHandleByName(out, port, server, handleName);
    const uint32_t bufferSize = getSymbolSize(out, port, server, handleName);
    const auto buffer = std::unique_ptr<uint8_t>(new uint8_t[bufferSize]);
    int result;

    const long status = AdsSyncReadReqEx2(port,
                                            &server,
                                            ADSIGRP_SYM_VALBYHND,
                                            handle,
                                            bufferSize,
                                            buffer.get(),
                                            &bytesRead);

    if (status) {
        out << "ADS read failed with: " << std::dec << status << '\n';
        return 0;
    }
    out << "ADS read " << std::dec << bytesRead << " bytes:" << std::hex;


    for (size_t i = 0; i < bytesRead; ++i) {
        out << ' ' << (int)buffer.get()[i];
    }

    std::memcpy(&result, buffer.get(), sizeof(result));

    out << " ---> " << result << '\n';

    releaseHandle(out, port, server, handle);

    return result;
}

结果:

Integer Function: readByNameInt():
ADS read 2 bytes: 85 ff ---> ff85

我使用一个几乎相同的函数来创建一个浮点数。这里的输出没有问题。 值如何显示为整数?

问候 蒂尔曼

【问题讨论】:

  • 那是因为std::hex。再次将std::dec 传递给流以将其设置回十进制。
  • 请不要将std::unique_ptr 用作简单的自删除指针,而是将智能指针视为所有权。在你的情况下,我宁愿推荐std::vector&lt;uint8_t&gt;

标签: c++ cout memcpy


【解决方案1】:

那是因为您更改了以下行中的输出基数:

out &lt;&lt; "ADS read " &lt;&lt; std::dec &lt;&lt; bytesRead &lt;&lt; " bytes:" &lt;&lt; std::hex;

行尾的std::hex 将应用于out 的每个后续输入流。

在打印最后一行之前将其改回十进制:

out << " ---> " << std::dec << result << '\n';

【讨论】:

    猜你喜欢
    • 2013-02-26
    • 2010-10-16
    • 2014-04-16
    • 2019-01-11
    • 1970-01-01
    • 2010-10-03
    相关资源
    最近更新 更多