Convert long to char* const - c++

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

Related

C++ Converting a String to unsigned char and convert it back to get the string

I hope I have clearly stated my goal in the topic and following is the code I am using.
#include <stdio.h>
#include <inttypes.h>
#include <iostream>
using namespace std;
int main() {
const char *data_ptr =(char*)"test";
const uint8_t* p = reinterpret_cast<const uint8_t*>(&data_ptr);
uint8_t* p1= const_cast<uint8_t*>(p);
char* p2 = reinterpret_cast<char*>(p1);
const char *final= const_cast<const char*>(p2);
string s1( data_ptr);
string s( reinterpret_cast<char const*>(p1),4) ;
cout<<"data_ptr is "<<data_ptr<<endl;
cout<<"p "<<p<<endl;
cout<<"p1 "<<p1<<endl;
cout<<"p2 "<<p2<<endl;
cout<<"final is "<<final<<endl;
cout<<"final1 is "<<s1.size() << "<-->"<<s.size()<<endl;
return 0;
}
and what it prints is as follows.
data_ptr is test
p X#
p1 X#
p2 X#
final is X#
final1 is 4<-->4
What should I do to get the "test" as a string.
As pointed out in the comments above, your data_ptr cast in line
const uint8_t* p = reinterpret_cast<const uint8_t*>(&data_ptr);
casts from a pointer to chars (char*) to a pointer of pointer of chars (in your case uint8_t*, referencing &data_ptr, which is in turn char*). That's also why your string s1 in
string s1( data_ptr);
Contains the correct test string, while s, as initialized in
string s( reinterpret_cast<char const*>(p1),4) ;
with p1 referencing the wrong pointer to pointer to chars from
const uint8_t* p = reinterpret_cast<const uint8_t*>(&data_ptr);
uint8_t* p1= const_cast<uint8_t*>(p);
is just initialized with garbage data.
So just change your line
const uint8_t* p = reinterpret_cast<const uint8_t*>(&data_ptr);
to
const uint8_t* p = reinterpret_cast<const uint8_t*>(data_ptr);
and both, s and s1 contain your source string "test".
"test" will not fit in an unsigned char. You should use the standard c functions atoi and itoa to do the conversion. You can also use these functions if you want to do it character by character.
I am not entirely sure what you are trying to do here. However, changing
const uint8_t* p = reinterpret_cast<const uint8_t*>(&data_ptr);
to
const uint8_t* p = reinterpret_cast<const uint8_t*>(data_ptr);
would do the job for you.
std::string has a constructor taking a char* or const char* as a parameter. It also has a function c_str() to do the conversion back to a char* so all thats needed is this:
const char* charptr = "Test";
string str(charptr);
const char* charptr2 = str.c_str();
//just to verify:
cout << charptr << "\n";
cout << str << "\n";
cout << charptr2 << "\n";
Edit: As you stated in the comments you need an uint8_t, for this just take the raw char* as it is:
const uint8_t* intptr = reinterpret_cast<const uint8_t*>(charptr);
Try it online: http://ideone.com/drJYuR

Print the results of MD5 function

I want to print MD5 for some string. For this I have done the the function
std::string generateHashMD5(std::string text)
{
unsigned char * resultHash;
resultHash = MD5((const unsigned char*)text.c_str(), text.size(), NULL);
std::string result;
result += (char *) resultHash;
return result;
}
Mow I want to print the result of this function. I try to version of such function.
void printHash(std::string hash)
{
for (unsigned i = 0; i < str.size(); i++)
{
int val = (short) hash[i];
std::cout<<std::hex<<val<<':';
}
std::cout<<std::endl;
}
std::string printHash(std::string hash)
{
char arrayResult[200];
for(int i = 0; i < 16; i++)
sprintf(&arrayResult[i*2], "%02x", (unsigned short int)hash[i]);
std::string result;
result += arrayResult;
return result;
}
The problem is that unfortunately none of it does not show correct result. What should be changed in this function or where is the mistakes?
You improperly use std::string as a buffer:
result += (char *) resultHash;
treats resultHash as a c-string, so if there is \0 byte in middle it would not get enough data. If there is no \0 byte you would copy too much and get UB. You should use constructor with size:
std::string result( static_cast<const char *>( resultHash ), blocksize );
where block size probably is 16. But I would recommend to use std::array<uint8_t,blocksize> or std::vector<uint8_t> instead os std::string, as std::string for buffer is very confusing.
in case if MD5 returns byte array
result += (char *) resultHash;
return result;
conversion to string will lose numbers after 0 because string constructor interprets input as null-terminated string
so vector can be used or string construction with explicit number of characters.
Still, there are not enough information to say exactly

unsigned char* to double in c++

I am copying double value into unsigned char* in the following way.
unsigned char* cmdBody;
double val = (double)-1;
std::ostringstream sstream;
sstream << val;
std::string valString = sstream.str();
unsigned int dataSize = valString.size() + 1;
cmdBody = (unsigned char*)malloc(dataSize);
memset(cmdBody, 0, dataSize);
memcpy(cmdBody, (unsigned char*)valString.c_str(), dataSize - 1);
cmdBody[dataSize - 1] = '\0';
From cmdBody I need to convert the value into double type. How to do it?
C much?
Your solution is very simple if you just use a std::string:
const auto val = -1.0; // Input double
const auto cmdBody = std::to_string(val); // Convert double to a std::string
const auto foo = std::stod(cmdBody); // Convert std::string to a double
It's important to note that there is no need to allocate, memcopy, or null-terminate when constructing a std::string. Which vastly simplifies your code.
Use std::stod, something like this:
#include <string>
double d = std::stod(cmdBody);
std::istringstream istream(std::string("3.14"));
double d;
istream >> d;
if (!istream.fail())
{
// convertion ok
}

Dereferencing an unsigned char pointer and storing its values into a string

So I am working on a tool that dereferences the values of some addresses, it is in both C and C++, and although I am not familiar with C++ I figured out I can maybe take advantage of the string type offered by C++.
What I have is this:
unsigned char contents_address = 0;
unsigned char * address = (unsigned char *) add.addr;
int i;
for(i = 0; i < bytesize; i++){ //bytesize can be anything from 1 to whatever
if(add.num == 3){
contents_address = *(address + i);
//printf("%02x ", contents_address);
}
}
As you can see what I am trying to do is dereference the unsigned char pointer. What I want to do is have a string variable and concatenate all of the dereferenced values into it and by the end instead of having to go through a for case for getting each one of the elements (by having an array of characters or by just going through the pointers) to have a string variable with everything inside.
NOTE: I need to do this because the string variable is going to a MySQL database and it would be a pain to insert an array into a table...
Try this that I borrowed from this link:
http://www.corsix.org/content/algorithmic-stdstring-creation
#include <sstream>
#include <iomanip>
std::string hexifyChar(int c)
{
std::stringstream ss;
ss << std::hex << std::setw(2) << std::setfill('0') << c;
return ss.str();
}
std::string hexify(const char* base, size_t len)
{
std::stringstream ss;
for(size_t i = 0; i < len; ++i)
ss << hexifyChar(base[i]);
return ss.str();
}
I didn't quite understand what you want to do here (why do you assign a dereferenced value to a variable called ..._address)?.
But maybe what you're looking for is a stringstream.
Here's a relatively efficient version that performs only one allocation and no additional function calls:
#include <string>
std::string hexify(unsigned char buf, unsigned int len)
{
std::string result;
result.reserve(2 * len);
static char const alphabet[] = "0123456789ABCDEF";
for (unsigned int i = 0; i != len)
{
result.push_back(alphabet[buf[i] / 16]);
result.push_back(alphabet[buf[i] % 16]);
{
return result;
}
This should be rather more efficient than using iostreams. You can also modify this trivially to write into a given output buffer, if you prefer a C version which leaves allocation to the consumer.

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