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

时间:2019-12-09 08:53:33

标签: c++ cout memcpy

我使用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

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

问候 蒂尔曼

1 个答案:

答案 0 :(得分:1)

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

[{k:v} for k,v in somedict[0].items() if 'Iron Man' in str(v)] >>>[{'key_three': {'inside_key_three': {'from_asguard': 'is not Iron Man'}}}]

该行末尾的out << "ADS read " << std::dec << bytesRead << " bytes:" << std::hex;将应用于随后到std::hex的每个输入流。

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

out