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

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

问题描述

我的应用程序需要将双精度值转换为 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* 存在一些混淆.char* 将是写入管道的 fwrite 函数的参数.

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.

推荐答案

如果要打印 double 类型可以支持的任何数字,请使用任何库来完成这项工作.它可以节省您的理智:为什么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?

如果您想以 double 类型打印数字的子集.例如,小数点后最多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.

如果您最初的目的是发送数据进行通信,那么发送 double 的二进制形式将是最快和最准确的方法(不会因转换而损失精度).其他答案中解释了执行此操作的方法.

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天全站免登陆