确定__i64toa_s的缓冲区大小

Determine buffer size for __i64toa_s

本文关键字:缓冲区 i64toa 确定      更新时间:2023-10-16

我想将一些数字从__int64转换为char。为此,我想使用函数__i64toa_s,正如MS所建议的那样。该函数期望返回值有一个char缓冲区。如何确定此缓冲区所需的最小大小?我不想因为缓冲区太小而出错,但我也不想浪费空间
非常感谢。

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

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

然而,由于您使用的是C++,在我看来,使用C++解决方案并避免以null结尾的C字符串更有意义。我认为没有理由使用__i64toa_s。请改用字符串流。

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

它通过促进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 -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);