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

'cout' displays integer as hex

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

代码:

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';