I am converting double values to string like this:
std::string conv(double x) {
char buf[30];
sprintf(buf, "%.20g", x);
return buf;
}
I have hardcoded the buffer size to 30, but am not sure if this is large enough for all cases.
- How can I find out the maximum buffer size I need?
- Does the precision get higher (and therefore buffer needs to increase) when switching from 32bit to 64?
PS: I cannot use ostringstream or boost::lexical_cast for performance reason (see this)
It is. %.20g specifies 20 digits in the mantissa. add 1 for decimal point. 1 for (possible) sign, 5 for “e+308” or “e-308”, the worse case exponent. and 1 for terminating null.
20 + 1 + 1 + 5 + 1 = 28.
No.
A double is the same size in both architectures. If you declare your variables as long double, then you possibly have 1 more digit in the exponent “e+4092”, which still fits in a 30 character buffer. But only on X86, and only on older processors.
The long double is an obsolete 80 bit form of floating point value that was the native format of the 486 FPU. That FPU architecture didn’t scale well and as since been discarded in favor of SSE style instructions where the largest possible floating point value is a 64 bit double.
Which is a long way of saying a buffer of 30 characters will always be sufficient as long as you keep limiting the mantissa in your printout to 20 digits.