What would be the code to convert an std::string to unsigned char* and back?
str = "1234567891234567"
unsigned char* unsignedStr = ConvertStrToUnsignedCharPointer(str);
str1 = ConvertUnsignedCharToStr(unsignedStr);
str
and str1
must be same with no loss of precision.
The strtoul() function converts a character string to an unsigned long integer value. The parameter nptr points to a sequence of characters that can be interpreted as a numeric value of type unsigned long int. The strtoull() function converts a character string to an unsigned long long integer value.
strcpy will result in the characters in the original string being reinterpreted as unsigned char .
However, from i=128:255 the chars and the unsigned chars cannot be casted, or you would have different outputs, because unsigned char saves the values from [0:256] and char saves the values in the interval [-128:127]).
The utoa() function coverts the unsigned integer n into a character string. The string is placed in the buffer passed, which must be large enough to hold the output. The radix values can be OCTAL, DECIMAL, or HEX.
auto str1 = std::string{"1234567891234567"}; // start with string
auto chrs = str.c_str(); // get constant char* from string
auto str2 = std::string{ chrs }; // make string from char*
Unsigned char*:
auto uchrs = reinterpret_cast<unsigned char*>(const_cast<char*>(chrs));
Using vectors instead of raw pointers:
using namespace std;
auto str1 = string{"1234567891234567"};
vector<char> chars{ begin(str1), end(str1) };
vector<unsigned char> uchars;
transform(begin(str1), end(str1), back_inserter(uchars),
[](char c) { return reinterpret_cast<unsigned char>(c); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With