确定__i64toa_s的缓冲区大小

时间:2013-11-29 11:10:50

标签: c++

我想将一些数字从__int64转换为char。为此,我想使用MS建议的函数__i64toa_s。该函数需要一个char缓冲区作为返回值。如何确定此缓冲区所需的最小大小?由于缓冲区太小,我不想得错,但我也不想浪费空间 谢谢!

3 个答案:

答案 0 :(得分:2)

您可以简单地计算__int64值中的位数。如果log10(value) + 1过载log10,则按循环或__int64

答案 1 :(得分:1)

假设十进制输出,则需要至少21个字符的缓冲区。对于64位整数,您需要允许19位数字表示为十进制,减号和空终止符。

但是,由于您使用的是C ++,因此我觉得使用C ++解决方案并避免以空值终止的C字符串更有意义。我认为没有理由使用__i64toa_s。改为使用字符串流。

答案 2 :(得分:1)

我会建议一个更通用的元函数,每当我需要时我都会使用它。

通过促进std::numeric_limits<>计算基数10中任何数值积分类型的最大存储大小:

/** @short Metafunction that calculates the maximum storage size for a string
 *  representation of a numerical type in base10, eventually including the sign.
 *
 *  @tparam T integral type, forwarded to std::numeric_limits<>
 *  @tparam null_inclusive whether to include the terminating null-character
 *  into the storage size
 */
template<typename T, bool null_inclusive = true>
struct digits10_storage_size:
  std::integral_constant<
    std::size_t,
    // note: digits10 returns the number of deciaml digits that the type can
    // represent without loss of precision, i.e. for char we get 2 digits (0..99)
    //
    // so we add here 1 to get 3 digits because [100..255] are 3 digits.
    // we add another time 1 because of an eventual sign (+/-) that a conversion
    // function could produce, plus finally the trailing \0-character eventually
    std::numeric_limits<T>::digits10 + 2 + null_inclusive
  >
{};

我看到的优点:

  • 编译时解决方案
  • 无论编译器/平台
  • ,都是完全符合类型而不是猜测的固定缓冲区
  • 通过使用元编程技术,甚至可以将这个元函数推广到不同的基数

用法:

char szNum[digits10_storage_size<__int64>::value];
_i64toa_s(i, szNum, 10);
// ... or use "unsafe" version because of correctly precomputed buffer:
_i64toa(i, szNum, 10);