【发布时间】:2015-12-30 13:24:47
【问题描述】:
如何在 c 中将字符串 0x26B70A40 转换为 int?
const char s[13] = "0x26B70A40";
int x = someFunction(s);
printf("%d\n", x);
那应该打印649529920。
【问题讨论】:
-
查看 strtoul(3)
如何在 c 中将字符串 0x26B70A40 转换为 int?
const char s[13] = "0x26B70A40";
int x = someFunction(s);
printf("%d\n", x);
那应该打印649529920。
【问题讨论】:
您需要使用来自stdlib.h 的strtol() 函数。
摘自手册页,
字符串可以以任意数量的空格(由 isspace(3) 确定)开头,后跟一个可选的
'+'或'-'符号。 如果基数为 0 或 16,则字符串可能包含"0x"前缀,数字将以 16 为基数读取; [....]
【讨论】:
您可以使用内置函数 strtol(char *str, char *end, int base)。
int x = strtol(s,NULL,16);
【讨论】:
尝试使用strtol()函数:
const char *hexstring = "0x26B70A40";
int x = (int)strtol(hexstring, NULL, 0);
【讨论】:
试试这个:
const char s[13] = "0x26B70A40";
char **ptr;
long val;
val = strtol(s, ptr, 16);
【讨论】:
strtol()已经在三个答案中被推荐过,这段代码也是不正确的。 str 不存在,ptr 被统一化。 prt 应该是 char* 类型,然后如果需要传递 '&prt`,但在这种情况下没有任何作用,因此可以传递 NULL。