Hi everybody,
I have a custom type-safe string format function and actually using fixed buffer of 2048 to sprintf.
How to know the exact number of character needed to write float, double and integers?
Thank you!
Knowing the exact number of character needed to write float, double and integers
For integers it's pretty easy:
// Determine log(value)/log(base)
Size logBase;
if ( nonZero )
{
logBase = 0;
for ( ValueType power = value; power != 0; power /= tBase )
logBase++;
}
else
{
logBase = 1;
}
const Size prefixLength = getNumberPrefixLengthForBase( base ); // e.g. 0x for hex
const Size stringLength = logBase + hasSign + prefixLength;
Floating point is more difficult, and will depend on how exactly you round/format the string. For example, you might have a value of 0.999 that you want to print with 2 decimal digits. This would round to 1. Do you want to display 1.00, or 1? Determining how many digits in a robust way for all values is not trivial. It takes 50+ lines of code for my implementation to do this, handing different rounding modes and exponent formats and bases. The crux of it is:
const Size prefixLength = getNumberPrefixLengthForBase( base );
Size stringLength = hasSign + prefixLength + numDigits + // sign, base prefix, significant digits.
(numDecimalDigits != 0) + numDecimalDigits; // decimal point and decimal digits.
if ( numExponentDigits > 0 )
stringLength += (exponent < ValueType(0)) + numExponentDigits + 1;
This is the maximum length of the string which is used to allocate a buffer. It might be shortened once the digits are actually generated (e.g. the 0.999 → 1 case mentioned above).
Note that I don't include the null terminator in any of the above calculations.