strtoul ()-strtoull ()- 将字符串转换为无符号长整数和无符号长整数

格式 (strtoul())

#include <stdlib.h>
unsigned long int strtoul(const char *nptr, char **endptr, int base);

格式 (strtoull())

#include <stdlib.h>
unsigned long long int strtoull(char *string, char **endptr, int base);

语言级别

ANSI

线程安全

语言环境敏感

这些函数的行为可能受当前语言环境的 LC_CTYPE 类别影响。 有关更多信息,请参阅 了解 CCSID 和语言环境

描述

strtoul() 函数将字符串转换为无符号长整数值。 参数 nptr 指向可以解释为无符号长整型的数字值的字符序列。

strtoull() 函数将字符串转换为无符号长整型整数值。 参数 nptr 指向可以解释为无符号长整型整数类型的数字值的字符序列。

使用这些函数时, nptr 参数应指向具有以下格式的字符串:

读取语法图跳过可视语法图空格 +  – 00x0X数字

如果 base 参数是介于 2 与 36 之间的值,那么主体序列的期望格式是表示基数参数指定的整数的字母和数字序列。 此序列可选择以正 (+) 或负 (-) 符号开头。 从 a 到 z 的字母 (大写或小写) 归为值 10 到 35。 只允许其归因值小于基本参数的字母。 如果 base 参数的值为 16 ,那么字符 0x0X (可选) 在字母和数字序列之前,后跟正 (+) 或负 (-) 符号 (如果存在)。

如果 base 参数的值为 0 ,那么字符串将确定 base。 在可选前导符号后,前导 0 指示八进制转换,前导 0x0X 指示十六进制转换,所有其他前导字符都会导致十进制转换。

这些函数将字符串扫描到与基本参数不一致的第一个字符。 此字符可能是字符串末尾的空字符 ('\0') 。 将忽略前导空格字符,并且可选的符号可以在数字之前。

如果 endptr 参数的值不是空指针,那么结束扫描的字符的指针将存储在 endptr 指向的值中。 如果无法形成值,那么 endptr 指向的值将设置为 nptr 参数。

返回值

如果 base 具有无效值 (小于 0 , 1 或大于 36) ,那么 errno 将设置为 EINVAL 并返回 0。 endptr 参数指向的值设置为 nptr 参数的值。

如果该值超出可表示值的范围,那么 errno 将设置为 ERANGE。 strtoul() 函数将返回 ULONG_MAX , strtoull() 函数将返回 ULONGLONG_MAX。

如果未转换任何字符,那么 strtoull() 函数将 errno 设置为 EINVAL 并返回 0。 strtoul() 函数将返回 0 ,但不会将 errno 设置为 EINVAL。 在这两种情况下, endptr 指向的值都设置为 nptr 参数的值。 成功完成后,这两个函数都会返回转换后的值。

示例

此示例将字符串转换为无符号长整型值。 它将显示已转换的值以及停止转换的子串。
#include <stdio.h>
#include <stdlib.h>
 
#define BASE 2
 
int main(void)
{
   char *string, *stopstring;
   unsigned long ul;
 
   string = "1000e13 e";
   printf("string = %s\n", string);
   ul = strtoul(string, &stopstring, BASE);
   printf("   strtoul = %ld (base %d)\n", ul, BASE);
   printf("   Stopped scan at %s\n\n", stopstring);
}
 
/*****************  Output should be similar to:  *****************
 
string = 1000e13 e
   strtoul = 8 (base 2)
   Stopped scan at e13 e
*/

相关信息