在C ++中将double转换为char *,具有高性能 [英] Converting double to char* in C++ with high performance

查看:1249
本文介绍了在C ++中将double转换为char *,具有高性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序需要将double值转换为char *,以便写入只接受字符的管道。通常的方法是使用 sprintf()函数或使用iomanip.h头文件中的 ostringstream

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.

有没有其他功能我可以使用?我可以使用什么逻辑来编写高效的转换函数?我唯一设法想出了到目前为止是使用除法和mod操作得到每个单独的数字,并将这些数字附加到一个char *,以获得整个双精度值。

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.

预先感谢您的想法。

编辑:对于如何使用char *有一些混乱。

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.

推荐答案

如果要打印任何数字,双类型可以支持,使用任何库都可以做的工作。它可以节省您的理智:为什么dtoa.c包含这么多的代码?

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?

如果你想打印双重类型的数字子集。例如,小数点后最多4位,小数点前不超过5位,然后可以舍入数字并转换为int类型,然后使用除法和mod打印出来。我可以确认此方法的效果。

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.

这篇关于在C ++中将double转换为char *,具有高性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆