How to create streambuf with array of unsigned char in C++

1k Views Asked by At

I want to create a std::istream object with a stream buffer object that can take raw byte data from array of unsigned char. I searched and found this Link

However they create the stream buffer based on array char:

struct membuf : std::streambuf
{
    membuf(char* begin, char* end) {
        this->setg(begin, begin, end);
    }
};

I thought about type caste , but i don't want to modify the original data.So how i can it be done using unsigned char.

1

There are 1 best solutions below

0
pptaszni On

With std::istream you cannot use unsigned char explicitly, because it is a typedef for std::basic_istream<char> docs. You can cast your buffer pointers to char*

this->setg(reinterpret_cast<char*>(begin), reinterpret_cast<char*>(begin), reinterpret_cast<char*>(end));

Note that conversion of values greater than CHAR_MAX to char is implementaion defined (of course, only if you will actually use this values as char).

Or you can try to use std::basic_istream<unsigned char> (I have not tried it though).