c++ - 'cout'将整数显示为十六进制

标签 c++ cout memcpy

我使用memcpy将多个字节合并为一个整数。该《准则》似乎行之有效,值(value)可以毫无问题地用于进一步的计算。但是,如果我使用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

我使用几乎相同的函数来创建浮点数。在这里,输出工作正常。
该值如何显示为整数?

问候语
蒂尔曼

最佳答案

这是因为您在以下行中更改了输出的基础:
out << "ADS read " << std::dec << bytesRead << " bytes:" << std::hex;
该行末尾的std::hex将应用于out的每个后续输入流。

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

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

关于c++ - 'cout'将整数显示为十六进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59245365/

相关文章:

c++ - 使用 libcurl 多接口(interface)连续请求相同的 "easy"句柄

c++ - 将 C++ 字符串解析为元组

printf - 我可以让 printf 格式像 C++ 流一样 float 吗

c - 为什么 memcpy 返回的字符串永远不等于数组中存在的相同字符串?

opencv - 了解 memcpy() 完成的复制

c++ - 如何从 C++ 程序内部测量内存使用情况?

c++ - luabind 0.9.1 迭代器总是只弹出最后一个对象

c++ - 知道将哪个ostream传递给函数c++

c++ - 为什么打印c样式字符串的 'address of index n'导致输出子字符串

使用 memcpy 与直接方法复制结构数组