使用std :: stringstream读取/写入无符号字节

时间:2012-11-01 18:28:56

标签: c++ stringstream binaryreader binarywriter

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

我需要写的信息涉及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 ++。

谢谢!

1 个答案:

答案 0 :(得分:0)

以下在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 按任意键继续 。 。

我认为你想要的是什么。

相关问题