确定__i64toa_s的缓冲区大小
Determine buffer size for __i64toa_s
我想将一些数字从__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);
相关文章:
- C++字符*缓冲区的大小
- 为什么msgrcv()将垃圾字符馈送到缓冲区
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- ostream过载时的缓冲区冲洗
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- Xaudio2在更改缓冲区或循环时弹出声音
- 为什么我在leetcode上收到AddressSanitizer:地址0x602000000058上的堆缓冲区溢出错误
- 如何将图像传输到c++(dll)中的缓冲区,然后在c#的缓冲区中读/写
- 如何在cpp.中使用协议缓冲区存储大缓冲区/数组(char/int)
- 多线程双缓冲区
- Android P-9.0.0_r53 Logcat主缓冲区超出定义大小
- 套接字读取后,我在缓冲区中看到意外输入
- std::带有自定义缓冲区的 iostream 不允许我写入
- 从返回的顶点缓冲区查询顶点结构
- Vulkan 中的动态顶点缓冲区格式设置
- OpenGL 16 位模板缓冲区?
- 在 leetcode 上提交解决方案时出现堆栈缓冲区溢出错误
- 在 openGL 中多次绑定缓冲区
- struct.error:解压缩 C++ 结构时,解包需要 288 字节的缓冲区
- 为什么缓冲区的内容在读取空 rdbuf 时被删除?