how to convert string to hexadecimal?

c
47,251

Solution 1

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"));

Solution 2

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

Solution 3

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.
}
Share:
47,251
user1390048
Author by

user1390048

Updated on July 05, 2022

Comments

  • user1390048
    user1390048 almost 2 years

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

  • user1390048
    user1390048 almost 12 years
    do i need to put SCNx32 in the syntax? do i need to have that if condition? cant i jus use sscanf(str, "0x%x", &value)?
  • Jonathan Grynspan
    Jonathan Grynspan almost 12 years
    If you are scanning into a uint32_t directly, you must use "%"SCNx32 or you risk undefined behaviour. If you are scanning into an unsigned int, you can use "%x". However, for maximum portability, you should use at least an unsigned long (scanned with "%lx") since not all systems have 32-bit unsigned ints. If you choose that route for whatever reason, you can assign the value of the unsigned int or unsigned long to your uint32_t variable after sscanf() returns.