Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting double to char* in C++ with high performance

My application needs to convert double values to char* to write to a pipe that accepts only characters. The usual ways of doing this are using the sprintf() function or using ostringstream from iomanip.h header file.

Turns out, both of these have really bad performance. And my application needs to do this conversion so often that it becomes the primary bottleneck.

Is there any other function I could use? What logic can I use to write an efficient conversion function? The only thing I have managed to come up with so far is to get each individual digit out using division and mod operations, and append these digits to a char* to get the entire double value. This doesn't seem like a good approach though, and will likely have bad performance itself.

Thanks in advance for your thoughts.

EDIT: There is some confusion over how the char* will be used. The char* will be an argument to the fwrite function which writes to a pipe.

like image 320
Shailesh Tainwala Avatar asked May 25 '12 06:05

Shailesh Tainwala


1 Answers

If you want to print any number that double type can support, use whatever library out there to do the job. It saves your sanity: Why does "dtoa.c" contain so much code?

If you want to print a subset of numbers in double type. For example, up to 4 digits after decimal point, and not more than 5 digits before decimal point, then you can round the number and convert to int type, before printing it out using division and mod. I can confirm the performance of this method.


EDIT: If you original purpose is to send the data for communication, then sending the binary form of double will be the fastest and most accurate method (no possible loss of precision due to conversion). The way to do this is explained in other answers.

like image 52
nhahtdh Avatar answered Sep 29 '22 10:09

nhahtdh