文章目录
随着64位程序的日益普遍,普通的计数范围不涉及需要64位整数表达,但是64位的地址,却是非常普遍的,需要引起我们的注意,在使用C++时,如何将64位(有符号无符号)整数转字符串,或者64位字符串转为(有符号无符号)整数。主要使用VS下的标准库。如下所示:
1.字符串转无符号整数
- 1.字符串转无符号整数
- 2.字符串转符号整数
- 3.整数转字符串
使用到的函数是strtoul或者strtoull:解释str指向的字节字符串中的无符号整数值。
#inlcude
unsigned long strtoul(const char * str,char ** str_end,int base);(直到C99)
unsigned long strtoul(const char * restrict str,char ** restrict str_end,int base);(自C99以来)
unsigned long long strtoull(const char * restrict str,char ** restrict str_end,int base);(自C99以来)
char * pEnd;
unsigned __int64 ui64 = strtoull("5b9550", &pEnd, 16);
参数,str_end:对类型为对象的引用char*,其值由函数设置为str中数值后的下一个字符。此参数也可以是空指针,在这种情况下不使用它。使用范例如下:
#include
#include
#include
int main(void)
{
const char *p = "10 200000000000000000000000000000 30 -40";
printf("Parsing '%s':\n", p);
char *end;
for (unsigned long i = strtoul(p, &end, 10);
p != end;
i = strtoul(p, &end, 10))
{
printf("'%.*s' -> ", (int)(end-p), p);
p = end;
if (errno == ERANGE){
printf("range error, got ");
errno = 0;
}
printf("%lu\n", i);
}
}
//结果
Parsing '10 200000000000000000000000000000 30 -40':
'10' -> 10
' 200000000000000000000000000000' -> range error, got 18446744073709551615
' 30' -> 30
' -40' -> 18446744073709551576
2.字符串转符号整数
使用到的函数是strtol或者strtoll:解析 C 字符串str ,将其内容解释为指定base的整数,它作为 type 的值返回long long int。如果endptr不是空指针,该函数还会将endptr的值设置为指向数字后的第一个字符。
long long int strtoll (const char* str, char** endptr, int base);
与无符号整数使用模式一样。
3.整数转字符串使用到的函数是_i64toa,_ui64toa,_atoi64,_strtoui64,这些是在VSC++环境下所拥有的函数,原型如下:
#include
_CRTIMP _CRT_INSECURE_DEPRECATE(_i64toa_s) char * __cdecl _i64toa(_In_ __int64 _Val, _Pre_notnull_ _Post_z_ char * _DstBuf, _In_ int _Radix);//64位整数转字符串
_CRTIMP _CRT_INSECURE_DEPRECATE(_ui64toa_s) char * __cdecl _ui64toa(_In_ unsigned __int64 _Val, _Pre_notnull_ _Post_z_ char * _DstBuf, _In_ int _Radix);//无符号64位整数转字符串
_Check_return_ _CRTIMP __int64 __cdecl _atoi64(_In_z_ const char * _String);//字符串转64位整数
_Check_return_ _CRTIMP __int64 __cdecl _strtoi64(_In_z_ const char * _String, _Out_opt_ _Deref_post_z_ char ** _EndPtr, _In_ int _Radix);//字符串转64位整数
_Check_return_ _CRTIMP unsigned __int64 __cdecl _strtoui64(_In_z_ const char * _String, _Out_opt_ _Deref_post_z_ char ** _EndPtr, _In_ int _Radix);//字符串转无符号64位整数
合理的脚本代码可以有效的提高工作效率,减少重复劳动。