【问题标题】:Reading/Writing unsigned bytes with std::stringstream使用 std::stringstream 读取/写入无符号字节
【发布时间】:2012-11-01 18:28:56
【问题描述】:

我正在尝试将无符号字符写入字符串流。

我需要写的信息涉及0x00。我需要将值 0 到 40 写为实际数值,而不是 ASCII 字符。

编辑:澄清一下,我写的不仅仅是 0-40 的值。它必须是二进制的。进来的这些东西需要保持原样,而不是一旦写入流就变成字符......

以下是我正在做的事情的要点。

TCHAR _buffer[2];    // This is part of the problem, I figure, since its a char
_buffer[0] = 0x00;
_buffer[1] = 0x01;

tstringstream s;

s.write(_buffer, sizeof(_buffer));

最终发生的是 0x00 导致字符串流结束,而 0x01 似乎永远不会到达那里。

我正在以类似的方式阅读:

stream.readsome(_buffer, sizeof(_buffer));

它似乎不想玩得很好,因为正在写入 0x00 并导致整个事情刚刚结束。

就是这样,还是我错过了什么?我尝试过使用 ios_base::binary,也尝试过使用 uint8_t 而不是 TCHAR,但这似乎会造成转换等混乱。我担心这可能是需要的路线,但我想在开始之前确定。

长话短说,我正在尝试找到一个与 C# 的 BinaryReader/Writer 等效的 C++。

谢谢!

【问题讨论】:

    标签: c++ stringstream binaryreader binarywriter


    【解决方案1】:

    以下是在VS2012上编译的:

    #include <iostream>
    #include <sstream>
    #include <string>
    
    int main()
    {
        wchar_t buf[] = { 0x0, 0x1, 'a', 'b', 'c' };
    
        std::wstring s(buf);
    
        std::wstringstream ss;
    
        ss.write(buf, 5);
    
        const std::wstring& chars = ss.str();
    
        for (std::wstring::const_iterator it = chars.begin(); it != chars.end(); ++it)
            std::cout << std::hex << *it << '\n';
    

    }

    给予

    0 1 61 62 63 按任意键继续 。 . .

    我认为这就是你想要的。

    【讨论】:

    • 嗯,这当然很有趣,因为这也是我所拥有的。也许我过激了,不应该相信调试器中显示的内容。那么问题可能实际上出在其他地方,可能是由于我稍后在读取值时所做的字符串转换......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-04
    • 2012-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多