簡體   English   中英

'cout' 將整數顯示為十六進制

[英]'cout' displays integer as hex

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

我使用幾乎相同的函數來創建一個浮點數。 這里的輸出工作沒有問題。 如何將值顯示為整數?

問候蒂爾曼

那是因為您在以下行中更改了輸出的基數:

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

該行末尾的std::hex將應用於out每個后續輸入流。

在打印最后一行之前將其改回十進制:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM