how to convert string to hexadecimal?

后端 未结 3 1434
难免孤独
难免孤独 2020-12-06 14:55

I have a string 0xFF, is there any function like atoi which reads that string and save in a uint32_t format?

相关标签:
3条回答
  • 2020-12-06 15:25

    you can also do it with a function like this.

    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;
    }
    

    example:

     printf("%08x\n",foo("0xff"));
    
    0 讨论(0)
  • 2020-12-06 15:39
    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.
    }
    
    0 讨论(0)
  • 2020-12-06 15:45
    #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;
    }
    
    0 讨论(0)
提交回复
热议问题