How to convert a string to Unsigned char in c++...
I have,
unsigned char m_Test[8];
I want to assign a string \"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
.
string uInput;
cout << "Enter message" << endl;
getline(cin, uInput);
I'm adding 1 here because in c strings we have '\0' at the end
unsigned char dataS[uInput.size()+1];
strcpy(reinterpret_cast<char*>(dataS), uInput.c_str());
I think this example will help others more in the future.