Convert hex string (char []) to int?

2019-01-03 02:08发布

I have a char[] that contains a value such as "0x1800785" but the function I want to give the value to requires an int, how can I convert this to an int? I have searched around but cannot find an answer. Thanks.

标签: c char int
10条回答
叼着烟拽天下
2楼-- · 2019-01-03 02:44

Use xtoi ( stdlib.h ). The string has "0x" as first two indexes so trim val[0] and val[1] off by sending xtoi &val[2].

xtoi( &val[2] );

查看更多
不美不萌又怎样
3楼-- · 2019-01-03 02:49

Have you tried strtol()?

strtol - convert string to a long integer

Example:

const char *hexstring = "abcdef0";
int number = (int)strtol(hexstring, NULL, 16);

In case the string representation of the number begins with a 0x prefix, one must should use 0 as base:

const char *hexstring = "0xabcdef0";
int number = (int)strtol(hexstring, NULL, 0);

(It's as well possible to specify an explicit base such as 16, but I wouldn't recommend introducing redundancy.)

查看更多
乱世女痞
4楼-- · 2019-01-03 02:49

i have done a similar thing, think it might help u its actually working for me

int main(){ int co[8],i;char ch[8];printf("please enter the string:");scanf("%s",ch);for(i=0;i<=7;i++){if((ch[i]>='A')&&(ch[i]<='F')){co[i]=(unsigned int)ch[i]-'A'+10;}else if((ch[i]>='0')&&(ch[i]<='9')){co[i]=(unsigned int)ch[i]-'0'+0;}}

here i have only taken a string of 8 characters. if u want u can add similar logic for 'a' to 'f' to give their equivalent hex values,i haven't done that cause i didn't needed it.

查看更多
别忘想泡老子
5楼-- · 2019-01-03 02:50

Assuming you mean it's a string, how about strtol?

查看更多
登录 后发表回答