Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ostream operator overloading for unsigned char in C++

Given:

typedef struct { char val[SOME_FIXED_SIZE]; } AString;
typedef struct { unsigned char val[SOME_FIXED_SIZE]; } BString;

I want to add ostream operator << available for AString and BString.

std::ostream & operator<<(std::ostream &out, const AString &str)
{ 
   out.write(str.val, SOME_FIXED_SIZE);
   return out;
}

If I do the same for BString, the compiler complains about invalid conversion from 'const unsigned char*' to 'const char*'. The ostream.write does not have const unsigned char* as argument.

It seems << itself accepts the const unsigned char, so I try something like this

std::ostream & operator<<(std::ostream &out, const BString &str)
{ 
    for (int i=0; i<SOME_FIXED_SIZE; i++)
    {
        out<<str.val[i];
    }
    return out;
}

Can someone tell me if this is right/good practice or there are some better ways? welcome any comments!

like image 873
pepero Avatar asked May 10 '26 05:05

pepero


1 Answers

The simplest and cleanest solution is to create an std::string, e.g.:

out << std::string(str.val, str.val + sizeof(str.val));

However, the question is: do you want formatted or unformatted output? For unformatted output, as ugly as it is, I'd just use a reinterpret_cast.

like image 130
James Kanze Avatar answered May 11 '26 18:05

James Kanze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!