0

If I have

char input[50] = "xFFFF";
int a;

How can I store the numerical value of input in a? the language is C.

Teddy
  • 579
  • 1
  • 4
  • 17

4 Answers4

4

One way to do it might be:

if (sscanf(input, "x%x", &a) == 0) {
    /* matching failed */
}

If your input uses a real hex specifier (like "0xFFFF") you can just use %i:

if (sscanf(input, "%i", &a) == 0) {
    /* matching failed */
}
cdhowie
  • 158,093
  • 24
  • 286
  • 300
2

You can use strtol function

char *ptr;
long a = strtol( input, &ptr, 16 );
DReJ
  • 1,966
  • 15
  • 14
1

One way:

#include <stdlib.h>

int main()
{
   char *p="xFFFF";
   long lng=strtol(&p[1], (char **)0, 16);
   printf("%ld\n", lng);
   return 0;
}
jim mcnamara
  • 16,005
  • 2
  • 34
  • 51
0

See C++ convert hex string to signed integer and if you're in a pure C environment, make sure to scroll down.

Community
  • 1
  • 1
Michael Repucci
  • 1,633
  • 2
  • 19
  • 35