Arun
Arun

Reputation: 2373

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?

Upvotes: 1

Views: 2631

Answers (3)

Jonathan Mee
Jonathan Mee

Reputation: 38909

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.

Upvotes: 4

Mati
Mati

Reputation: 61

std::istringstream istream(std::string("3.14"));
double d;
istream >> d;
if (!istream.fail())
{
// convertion ok
}

Upvotes: 0

Paul Evans
Paul Evans

Reputation: 27567

Use std::stod, something like this:

#include <string>
double d = std::stod(cmdBody);

Upvotes: 2

Related Questions