How to convert a string literal to unsigned char array in visual c++
Firstly, the array has to be at least big enough to hold the string:
unsigned char m_Test[20];
then you use strcpy. You need to cast the first parameter to avoid a warning:
strcpy( (char*) m_Test, "Hello World" );
Or if you want to be a C++ purist:
strcpy( static_cast <char*>( m_Test ), "Hello World" );
If you want to initialise the string rather than assign it, you could also say:
unsigned char m_Test[20] = "Hello World";
For all practical purposes, the strcpy answers are correct, with the note that 8 isn't big enough for your string.
If you want to be really pedantic, you might need something like this:
#include <algorithm>
int main() {
const char greeting[] = "Hello world";
unsigned char m_Test[sizeof(greeting)];
std::copy(greeting, greeting + sizeof(greeting), m_Test);
}
The reason is that std::copy will convert the characters in the original string to unsigned char
. strcpy will result in the characters in the original string being reinterpreted as unsigned char
. You don't say which one you want.
The standard permits there to be a difference between the two, although it's very rare: you'd need char
to be signed, in an implementation with a 1s' complement or sign-magnitude representation. You can pretty much ignore the possibility, but IMO it's worth knowing about, because it explains the funny warnings that good compilers give you when you mix up pointers to char
and unsigned char
.