Teddy
Teddy

Reputation: 597

How do I convert a string representation of a hex to its hex value in c?

If I have

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

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

Upvotes: 0

Views: 962

Answers (4)

cdhowie
cdhowie

Reputation: 168958

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 */
}

Upvotes: 4

DReJ
DReJ

Reputation: 1974

You can use strtol function

char *ptr;
long a = strtol( input, &ptr, 16 );

Upvotes: 2

jim mcnamara
jim mcnamara

Reputation: 16379

One way:

#include <stdlib.h>

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

Upvotes: 1

Michael Repucci
Michael Repucci

Reputation: 1663

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

Upvotes: 0

Related Questions