简体   繁体   English

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

[英]'cout' displays integer as hex

I use memcpy to merge multiple bytes into an integer.我使用 memcpy 将多个字节合并为一个整数。 The Code seems to work and value can be used for further calculations without any problems.该代码似乎有效,值可用于进一步计算而不会出现任何问题。 But if I display the result with cout, the value is displayed as hex:但是如果我用 cout 显示结果,则该值显示为十六进制:

Code:代码:

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

Result:结果:

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

I use an almost identical function to create a float.我使用几乎相同的函数来创建一个浮点数。 Here the output works without problems.这里的输出工作没有问题。 How can the value be displayed as an integer?如何将值显示为整数?

Greeting Tillman问候蒂尔曼

That's because you changed the base of the output in the following line:那是因为您在以下行中更改了输出的基数:

out << "ADS read " << std::dec << bytesRead << " bytes:" << std::hex;

The std::hex in the end of the line will apply to every subsequent input stream to out .该行末尾的std::hex将应用于out每个后续输入流。

Change it back to decimal before printing the last line:在打印最后一行之前将其改回十进制:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM