views:

182

answers:

1

So I would like to parse a binary file and extract some data from it. The problem I am facing with this is that I need to convert a stream of chars to a stream of unsigned chars. Reading the boost documentation, it seems that boost::iostreams::code_converter should be the solution for this, so I tried this:

typedef unsigned char uint8_t;
typedef boost::iostreams::stream<boost::iostreams::code_converter<
   boost::iostreams::basic_array_source<uint8_t>, 
   std::codecvt<uint8_t, char, std::mbstate_t> > > array_stream;

array_stream s; //initialized properly in the code
unsigned char asd;
s >> asd;
std::cout << asd << std::endl;

The idea was to specify a codecvt with InternalType=uint8_t and ExternalType=char. Unfortunately this does not compile. So the question is: how do I convert a stream of chars to a stream of uint8_ts?

+1  A: 

I don't know if you you still have this problem, but if you do, could you elaborate a little bit on what exactly you are trying to achieve. The thing is internally char and unsigned char are the same. They are just 8 bits sitting somewhere. No conversion is needed.

The only difference is in how the compiler interprets them when you use them. This means you should be able to solve most problems by using a static_cast at the time of usage.

For your information by the way, std::cout will output a unsigned char identical to a char. If you want the numerical value you have to cast it twice:

array_stream  s;   //initialized properly in the code
unsigned char asd;
s >> asd;

std:cout << int( asd );

I can see the inconvenience in this and possibly boost::iostreams has some way to do that for you, but I have never used boost::iostreams and looking at the number of answers here, not many can help you. If all else fails, just reinterpret the data. In any case converting it would be a bad idea if that meant copying it all.

ufotds
So I guess the bigger picture of the original question was that I wanted to give boost::spirit a stream of unsigned chars to parse. So putting static_casts all over the code whenever I try to read something off the stream is not viable (not my code is doing all the reading).I eventually worked around the problem by scrapping boost::iostreams and just using the iterator based parsers from spirit.
Zsol