Don't use std::string
to store binary data; that class is specifically designed for working with strings. It feels like there was original C code that was using a char
array to store a sequence of bytes and translated that to std::string
for C++. In this case, it's not being used as a string, so it doesn't make sense to store it in a std::string
.
From there, translating to an unsigned int
, well for starters, you can't simply cast it even if you were using a more primitive type such as a char *
, as it would violate the rules of strict aliasing resulting in undefined behavior. What you want to do is create a new variable and memcpy
the data into this new variable.
Here is the section from the C++14 standard working draft describing compatible types (3.10 p10):
If a program attempts to access the stored value of an object through a glvalue of other than one of the
following types the behavior is undefined:
54
— the dynamic type of the object,
— a cv-qualified version of the dynamic type of the object,
— a type similar (as defined in 4.4) to the dynamic type of the object,
— a type that is the signed or unsigned type corresponding to the dynamic type of the object,
— a type that is the signed or unsigned type corresponding to a cv-qualified version of the dynamic type
of the object,
— an aggregate or union type that includes one of the aforementioned types among its elements or non-
static data members (including, recursively, an element or non-static data member of a subaggregate
or contained union),
— a type that is a (possibly cv-qualified) base class type of the dynamic type of the object,
— a
char
or
unsigned char
type.
As you can see, it explicitly allows for accessing any object as a char
or unsigned char
, but it gives no such allowance to access a char
or unsigned char
as anything else.