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";
Cast a string to unsigned char in c++
Your first code doesn't work because there is no standard conversion operator defined for converting a std::string
to a unsigned char
. You need to actually parse the std::string
into a numeric value.
Your second code doesn't work because your std::stringstream
is not in std::hex
mode when reading decimal
from the stream, but even if it were, operator>>
treats an unsigned char
as a text character, not as an integer (same with operator<<
for output). So you need to use an actual integer type, such as short
or int
, which can hold the full value of the parsed numeric, eg:
string hex_str = "0x3d";
unsigned short temp;
stringstream my_ss;
my_ss << hex_str;
my_ss >> hex >> temp;
unsigned char decimal = temp;
That being said, I would suggest using std::istringstream
instead, eg:
#include <string>
#include <sstream>
#include <iomanip>
std::string a = "0x08";
unsigned short temp;
std::istringstream(a) >> std::hex >> temp;
BYTE Sample2 = static_cast<BYTE>(temp);
Demo
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
int main()
{
std::string hex_str = "0x3d";
unsigned short temp;
std::istringstream(hex_str) >> std::hex >> temp;
unsigned char decimal = static_cast<unsigned char>(temp);
std::cout << "The value is: " << static_cast<int>(decimal);
return 0;
}
Demo
Or, in C++11 and later, you can use std::stoi()
instead, eg:
#include <string>
std::string a = "0x08";
BYTE Sample2 = static_cast<BYTE>(std::stoi(a, nullptr, 16));
Demo
#include <iostream>
#include <string>
int main()
{
std::string hex_str = "0x3d";
unsigned char decimal = static_cast<unsigned char>(std::stoi(hex_str, nullptr, 16));
std::cout << "The value is: " << static_cast<int>(decimal);
return 0;
}
Demo
How to convert unsigned char* to an unsigned char array in C/C++?
you do need to convert anything. if you want to copy from one
void Example(const void *bytes, size_t len)
{
unsigned char buffer[2048];
memcpy(buffer, bytes, len);
/* ...*/
}
example usage
int foo(void)
{
char str[] = "Hello world";
Example(str, sizeof(str));
}
How to assign string to unsigned char[] in c++
Your sample code has either one or several problems with it if you are attempting to print out true
. How many depends on how you're trying to do that. My first two points apply if you are comparing text to other text. If you're trying to convert text to a number and compare numbers, ignore them.
unsigned char a[10]={0,1,2,3,4,5,6,7,8,9}; // 1
string b="5";
if(a[5]==(unsigned char)atoi(b.c_str())){ // 2
count<<true<<endl; // 3
}
1) While this will produce an array of unsigned characters, they won't be text values. The values in that array are the first 10 ASCII characters rather than the characters that produce '0' through '9' when printed. Those characters can be placed in your array with the code:
unsigned char a[10]={'0','1','2','3','4','5','6','7','8','9'};
Again, this is only provided you're trying to compare text data. If you're trying to convert to a number and compare the entries in this array with that number, you'll want your original array.
2) You are correct that a[5]
will access the sixth element of a
. If you are comparing text values and not numeric values, you need only to access the first element of your string for comparison. This is provided you know the string is at least 1 element in size. Since you defined it just above this code, that's fine, but in cases of user input, you'll need to check. The proper syntax for this comparison, again as deviantfan stated, is a[5] == b[0]
, because the []
operator on strings
will return a char
.
Once again, the above applies to your answer only if you're comparing text values. If you're comparing numeric values, your original code is correct.
3) You haven't placed quotation marks around the true
. While this will compile, and even print something--it won't be true
unless a few conditions are met that you're unlikely to encounter this early in your coding career. What you likely meant to put is "true", which will make the output print true. Also, you want cout
, not count
.
Here is a link to an example which compares the string and the (modified) character array, as text data. If you're comparing numeric data, the only thing wrong with your code is 3).
Incompatibility between char* and unsigned char*?
C++
is being strict in checking the types where std::strcpy
expects a char*
and your variable var
is an unsigned char*
.
Fortunately, in this case, it is perfectly safe to cast the pointer to a char*
like this:
std::strcpy(reinterpret_cast<char*>(var), "string");
That is because, according to the standard, char
, unsigned char
and signed char
can each alias one another.
Related Topics
Openssl::Ssl_Library_Init() Memory Leak
How to Properly Use System() to Execute a Command in C++
Why the Sequence-Operation Algorithms Predicates Are Passed by Copy
Why Are Designated Initializers Not Implemented in G++
Does Calling a Destructor Explicitly Destroy an Object Completely
How to Easily Indent Output to Ofstream
How to Convert a Byte Array into Double in C
Sub-Millisecond Precision Timing in C or C++
How to Take Ownership of an Abandoned Boost::Interprocess::Interprocess_Mutex
Erase Element in Vector While Iterating the Same Vector
Simple For() Loop Benchmark Takes the Same Time with Any Loop Bound
Calling an Explicit Constructor with a Braced-Init List: Ambiguous or Not
Boost.Python Call by Reference:Typeerror: No To_Python (By-Value) Converter Found for C++ Type:
#Error Please Use the /Md Switch for _Afxdll Builds