3

我有一个字符串0xFF,是否有类似atoi读取该字符串并以某种uint32_t格式保存的函数?

4

3 回答 3

5

您也可以使用这样的功能来做到这一点。

unsigned int foo(const char * s) {
 unsigned int result = 0;
 int c ;
 if ('0' == *s && 'x' == *(s+1)) { s+=2;
  while (*s) {
   result = result << 4;
   if (c=(*s-'0'),(c>=0 && c <=9)) result|=c;
   else if (c=(*s-'A'),(c>=0 && c <=5)) result|=(c+10);
   else if (c=(*s-'a'),(c>=0 && c <=5)) result|=(c+10);
   else break;
   ++s;
  }
 }
 return result;
}

例子:

 printf("%08x\n",foo("0xff"));
于 2012-05-24T23:29:34.127 回答
4
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

int main(void) {
    const char *hexValue = "0xFF";
    char *p;
    uint32_t uv=0;
    uv=strtoul(hexValue, &p, 16);
    printf("%u\n", uv);
    return 0;
}
于 2012-05-25T00:21:30.837 回答
2
const char *str = "0xFF";
uint32_t value;
if (1 == sscanf(str, "0x%"SCNx32, &value)) {
    // value now contains the value in the string--decimal 255, in this case.
}
于 2012-05-24T23:02:07.987 回答