简体   繁体   中英

Reading/Writing unsigned bytes with std::stringstream

I am trying to write unsigned chars to a stringstream.

The information I need to write has 0x00 involved. I need to be writing the values 0 thru 40 as actual numeric values, and not as ASCII characters.

EDIT: To clarify, I am writing more than just the values 0-40. It needs to be binary. This stuff coming in needs to stay as is, as opposed to being turned into chars once written to the stream...

Below is the jist of what I am doing.

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));

What ends up happening is the 0x00 causes the stringstream to be ended, and the 0x01 doesn't seem to ever get there.

I am reading in a similar manner:

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

and it seems to not want to play nice because of the 0x00 being written and causing the whole thing to just be ended.

Is that just the way it is, or am I missing something? I have tried using ios_base::binary, and have also tried using uint8_t instead of TCHAR, but that seems to create a mess of casting and such. I fear this might be the route that is required, but I want to be sure before I go doing it.

Long story short, I am trying to find a C++ equivalent to C#'s BinaryReader/Writer.

Thanks!

The following compiled on 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';

}

gives

0 1 61 62 63 Press any key to continue . . .

Which I think is what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM