Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert double to Char Array C++

I'm trying to convert (and round) a double to a char array without converting with a std::to_string on the double first. However, I'm receiving random memory text instead. What am I doing wrong?

Here is my code:

double d = 1.0929998; 
d = std::round(d * 100) / 100;

char s[sizeof(d)];
std::memcpy(s,&d,sizeof(d));

Result:

s: q=×£pñ?

Intended value:

s: 1.09

like image 501
Delrog Avatar asked Jun 06 '18 00:06

Delrog


People also ask

How do you make a double into a character?

A double cannot be converted to a char*. If you're simply trying to get a string representation of the double, you're going to have to convert it to a char array. A function accepting a char* will accept a char[].

How to copy a string to an array of char c++?

The c_str() and strcpy() function in C++ C++ c_str() function along with C++ String strcpy() function can be used to convert a string to char array easily. The c_str() method represents the sequence of characters in an array of string followed by a null character ('\0'). It returns a null pointer to the string.


2 Answers

You are translating the literal bytes of your double into chars. The double value is a binary representation (usually something like IEEE 754) while a char is a binary representation of a character (usually something based on ASCII). These two are not compatible.

Unfortunately, this means that you must do some kind of conversion process. Either the std::to_string() that you said you don't want to do, or a more complicated std::stringbuf (which will call std::to_string() under the hood anyway)

like image 172
tdk001 Avatar answered Sep 20 '22 11:09

tdk001


You are copying a double (which is a binary representation for a number) into a char array; there is no reason those bytes should correspond to digit characters.

like image 43
Scott Hunter Avatar answered Sep 17 '22 11:09

Scott Hunter