对于 uint32_t 和其他 stdint 类型,atoi 或 strtoul 的等效项是什么?
我正在寻找将字符串转换为 stdint.h 整数的标准函数,喜欢
int i = atoi("123");
unsigned long ul = strtoul("123", NULL, 10);
uint32_t n = mysteryfunction("123"); // <-- ???
i'm looking for the standard functions to convert a string to an stdint.h integer, like
int i = atoi("123");
unsigned long ul = strtoul("123", NULL, 10);
uint32_t n = mysteryfunction("123"); // <-- ???
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有两个常规选项:
strto[iu]max
,然后检查该值是否适合较小的类型,或者切换到sscanf
。 C 标准在
中定义了整个宏系列,这些宏扩展为
类型的适当转换说明符。uint32_t
示例:(对于
uint32_t
,strtoul
+ 溢出检查也适用于uint32_t
,因为 < code>unsigned long 至少为 32 位宽,它不能可靠地用于uint_least32_t
,uint_fast32_t
、uint64_t
等)编辑:正如下面 Jens Gustedt 所指出的,这并不能提供
strtoul
的全部灵活性code> 因为您无法指定基础。然而,基数 8 和基数 16 仍然可以分别通过SCNo32
和SCNx32
获得。There are two general options:
strto[iu]max
followed by a check to see if the value fits in the smaller type, or switch tosscanf
. The C standard defines an entire family of macros in<inttypes.h>
that expand to the appropriate conversion specifier for the<stdint.h>
types. Example foruint32_t
:(In the case of
uint32_t
,strtoul
+ overflow check would also work foruint32_t
becauseunsigned long
is at least 32 bits wide. It wouldn't reliably work foruint_least32_t
,uint_fast32_t
,uint64_t
etc.)Edit: as Jens Gustedt notes below, this doesn't offer the full flexibility of
strtoul
in that you can't specify the base. However, base 8 and base 16 are still possible to obtain withSCNo32
andSCNx32
, respectively.由于您的问题涉及无符号整数,因此溢出检查很简单。通过一些辅助函数,
您可以轻松定义宏,为您感兴趣的任何类型提供帮助
Since your question concerns
unsigned
integers the overflow check is simple. With a little helper functionyou easily can define macros that do the trick for any type you are interested in