std::hex 没有像我预期的那样工作

std::hex does not work as I expect

本文关键字:工作 hex std      更新时间:2023-10-16

我不习惯C++,所以请耐心等待...

从设备读取两个字节并进入缓冲区。然后打印出来。

下面的代码应该返回字符串"0x204D"但是,它返回"0x M",十六进制为 30 78 20 4d

因此,十六进制不会解码为 ascii。

void vito_unit::decodeAsRaw(unsigned char *buffer, int bufferLen)
{
    std::stringstream *decodedClearText;
    decodedClearText = new std::stringstream;
    *decodedClearText << "0x" << std::hex;
    for (int i=0; i<bufferLen; i++) {
            *decodedClearText << buffer[i];
    }
    setValue(decodedClearText->str());
}

应该怎么做?

这与

std::hex无关。

当您流式传输[signed/unsigned] char时,将使用其 ASCII 表示形式,因为这通常是char s的预期。

您可以通过将号码

转换为 int 来流式传输号码。然后以十六进制表示法呈现数字的功能(即 std::hex ( 将被触发。

您还应该修复内存泄漏和不必要的动态分配:

void vito_unit::decodeAsRaw(unsigned char const* const buffer, int const bufferLen)
{
    std::stringstream decodedClearText;
    decodedClearText << "0x" << std::hex;
    for (int i = 0; i < bufferLen; i++) {
       decodedClearText << +buffer[i];
    }
    setValue(decodedClearText.str());
}

一元"+"执行对int的积分提升。

buffer[i] 的类型为 unsigned char,因此打印为字符而不是其十六进制表示形式。可以将值强制转换为unsigned int以避免这种情况。

void vito_unit::decodeAsRaw(unsigned char *buffer, int bufferLen)
{
    std::stringstream *decodedClearText;
    decodedClearText = new std::stringstream;
    *decodedClearText << "0x" << std::hex;
    for (int i=0; i<bufferLen; i++) {
            *decodedClearText << (unsigned int) buffer[i];
    }
    setValue(decodedClearText->str());
}

Bo Persson的提示是我需要的。

 for (int i=0; i<bufferLen; i++) {
        *decodedClearText << (int)buffer[i];
}

做到了。