Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting from C++ string to unsigned char* and back

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.

like image 440
Sahil Avatar asked Nov 04 '15 13:11

Sahil


People also ask

How to Convert char to unsigned long in C?

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.

How to Convert string to unsigned char in c++?

strcpy will result in the characters in the original string being reinterpreted as unsigned char .

Can you cast unsigned char to 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]).

How do I turn an unsigned int into a string?

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.


1 Answers

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); });
like image 72
utnapistim Avatar answered Sep 28 '22 08:09

utnapistim