Search code examples
c++compiler-errorsrulesunsigned-char

Best way to create a string buffer for binary data


When I try the following, I get an error:

unsigned char * data = "00000000"; //error: cannot convert const char to unsigned char

Is there a special way to do this which I'm missing?

Update

For the sake of brevity, I'll explain what I'm trying to achieve:

I'd like to create a StringBuffer in C++ which uses unsigned values for raw binary data. It seems that an unsigned char is the best way to accomplish this. If there is a better method?


Solution

  • std::vector<unsigned char> data(8, '0');
    

    Or, if the data is not uniform:

    auto & arr = "abcdefg";
    std::vector<unsigned char> data(arr, arr + sizeof(arr) - 1);
    

    Or, so you can assign directly from a literal:

    std::basic_string<unsigned char> data = (const unsigned char *)"abcdefg";