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

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.

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); });

Related

Convert unsigned char to string then again to unsigned char

I want to convert:
A simple unsigned char [] to string
Then again to unsigned char
This is my code:
// This is the original char
unsigned char data[14] = {
0x68,0x65,0x6c,0x6c,0x6f,0x20,0x63,0x6f,0x6d,0x70,0x75,0x74,0x65,0x72,
};
// This convert to string
string str(data, data + sizeof data / sizeof data[0]);
// And this convert to unsigned char again
unsigned char* val = new unsigned char[str.length() + 1];
strcpy_s(reinterpret_cast<char *>(val), str.length()+1 , str.c_str());
The problem is with the 2nd part, It wont convert the string to unsigned char like it was before. I think this img from locals in debug helps
One way:
#include <string>
#include <utility>
#include <cstring>
#include <memory>
#include <cassert>
int main()
{
// This is the original char
unsigned char data[14] = {
0x68,0x65,0x6c,0x6c,0x6f,0x20,0x63,0x6f,0x6d,0x70,0x75,0x74,0x65,0x72,
};
// This convert to string
std::string str(std::begin(data), std::end(data));
// And this convert to unsigned char again
auto size = std::size_t(str.length());
auto new_data = std::make_unique<unsigned char[]>(size);
std::memcpy(new_data.get(), str.data(), size);
// check
for (auto f1 = data, f2 = new_data.get(), e1 = f1 + size ; f1 != e1 ; ++f1, ++f2)
{
assert(*f1 == *f2);
}
}

Marshaling - conversion std::vector<char> to string^ And conversely

I use 2 method for these conversion
// Vector to String.
VectorToString(std::vector<char> data)
{
const char* newData = &data[0];
String ^result;
result = marshal_as<String^>(newData);
return result;
}
// String to vector
StringToVector(String ^ data)
{
marshal_context ctx;
IntPtr p = Marshal::StringToHGlobalAnsi(data);
const char* pAnsi = static_cast<const char*>(p.ToPointer());
// use pAnsi
std::vector<char> result;
result.assign(pAnsi, pAnsi + strlen(pAnsi));
Marshal::FreeHGlobal(p);
return result;
}
with 2 above function I can doing convert.
can you tell me these conversion is correct? or not?
actually, this way for convert std::vector to String is best way?
you must be add #include msclr/marshal_cppstd.h
vector to String ^
vector<char> data;// this is be initialize
std::string myString = std::string(begin(data), end(data));
String^ result = marshal_as<String^>(myString);
string ^ to vector
marshal_context context;
std::vector<char> myVector;
const char* afterConvert = context.marshal_as<const char*>(data);
myVector.assign(afterConvert , afterConvert + strlen(afterConvert));

C++ regex - replacing substring in char

I have written the following function to replace substrings in a char. This way involves converting to a std::string then converting back to a const char. Is this the most efficient way or could I do it without this conversion or even a better way?!
const char* replaceInString(const char* find, const char* str, const char* replace)
{
std::string const text(str);
std::regex const reg(find);
std::string const newStr = std::regex_replace(text, reg, replace);
//Convert back to char
char *newChar = new char[newStr.size() + 1];
std::copy(newStr.begin(), newStr.end(), newChar);
newChar[newStr.size()] = '\0'; // terminating 0
return newChar;
}
const char* find = "hello";
const char* replace = "goodbye";
const char* oldStr = "hello james";
const char* newStr = m->replaceInString(find, oldStr, replace);
Assuming that you want a function to be called from a .c file you could use strdup (see code below).
#include <string>
#include <regex>
#include <cstdio>
#include <cstdlib>
char* replaceInString(char const *find, char const *str, char const *replace)
{
return strdup(std::regex_replace(std::string(str), std::regex(find), replace).c_str());
}
int main()
{
char *newStr = replaceInString("hello", "hello james", "goodbye");
printf("newStr = %s\n", newStr);
free(newStr);
return 0;
}
Note however that you have to free the returned memory after you're done.
Otherwise, as #jerry-coffin suggested go all the way with std::string (see code below):
#include <string>
#include <regex>
#include <iostream>
std::string replaceInString(std::string const &find, std::string const &str, std::string const &replace)
{
return std::regex_replace(std::string(str), std::regex(find), replace);
}
int main()
{
std::string str = replaceInString(std::string("hello"), std::string("hello james"), std::string("goodbye"));
std::cout << str << std::endl;
return 0;
}

C++ String and char * c stype strings

I have a c library which use char arrays as strings and i want to use c++ std::string on my code,
could someone help me how can i convert between char * c style strings and STL library strings ?
for example i have :
char *p="abcdef";
string p1;
and
string x="abc";
char *x1;
how can i convert p to p1 and x to x1
Use string's assignment operator to populate it from a char *:
p1 = p;
Use string's c_str() method to return a const char *:
x1 = x.c_str();
From char* to std::string :
char p[7] = "abcdef";
std::string s = p;
From std::string to char* :
std::string s("abcdef");
const char* p = s.c_str();
You can construct a std::string from a C string thus:
string p1 = p;
You can get a const char * from a std::string thus:
const char *x1 = x.c_str();
If you want a char *, you'll need to create a copy of the string:
char *x1 = new char[x.size()+1];
strcpy(x1, x.c_str());
...
delete [] x1;
string has a constructor and an assignment operator that take a char const* as an argument, so:
string p1(p);
or
string p1;
p1 = p;
Should work. The other way around, you can get a char const* (not a char*) from a string using its c_str() method. That is
char const* x1 = x.c_str();
#include <string.h>
#include <stdio.h>
// Removes character pointed to by "pch"
// from whatever string contains it.
void delchr(char* pch)
{
if (pch)
{
for (; *pch; pch++)
*pch = *(pch+1);
}
}
void main()
{
// Original string
char* msg = "Hello world!";
// Get pointer to the blank character in the message
char* pch = strchr(msg, ' ');
// Delete the blank from the message
delchr(pch);
// Print whatever's left: "Helloworld!"
printf("%s\n", msg);
}

Convert long to char* const

What is the right way to convert long to char* const in C++?
EDIT:
long l = pthread_self();
ThirdPartyFunction("Thread_Id_"+l); //Need to do this
ThirdPartyFunction(char* const identifierString)
{}
EDIT:
The "proper" way to convert an integer to a string, in C++, is to use a stringstream. For instance:
#include <sstream>
std::ostringstream oss;
ossĀ << "Thread_Id_" << l;
ThirdPartyFunction(oss.str().c_str());
Now, that probably won't be the "fastest" way (streams have some overhead), but it's simple, readable, and more importantly, safe.
OLD ANSWER BELOW
Depends on what you mean by "convert".
To convert the long's contents to a pointer:
char * const p = reinterpret_cast<char * const>(your_long);
To "see" the long as an array of chars:
char * const p = reinterpret_cast<char * const>(&your_long);
To convert the long to a string:
std::ostringstream oss;
oss << your_long;
std::string str = oss.str();
// optionaly:
char * const p = str.c_str();
Another possibile "pure" solution is to use snprintf
long number = 322323l;
char buffer [128];
int ret = snprintf(buffer, sizeof(buffer), "%ld", number);
char * num_string = buffer; //String terminator is added by snprintf
long l=0x7fff0000; // or whatever
char const *p = reinterpret_cast<char const *>(l);