Austin
Austin

Reputation: 7339

Shortest way to convert hex char to int in C?

I'm looking for the least amount of code in C, in order to convert a char to int, where it flags -1 (or any error flag) if the char is not a valid hex digit.

here's what I came up with, is there a shorter way?

// input example
char input = 'f';   

// conversion segment
int x = input - '0';    
if (!((x >= 49 && x <= 54) || (x >= 0 &&  x <= 9))) x = -1;
if (x > 9) x -= 39;

// test print   
printf("%d", x);

Upvotes: 0

Views: 960

Answers (2)

chux
chux

Reputation: 154280

This code assumes ASCII and converts all 256 characters codes into 256 different codes, partially '0'-'9' 'A'-'F' map to 0,1,...15.

For additional tricks and simplification see the post

unsigned char ch = GetData(); // Fetch 1 byte of incoming data;
if (!(--ch & 64)) {           // decrement, then if in the '0' to '9' area ...
  ch = (ch + 7) & (~64);      // move 0-9 next to A-Z codes
}
ch -= 54;                     // -= 'A' - 10 - 1
if (ch > 15) { 
  ; // handle error
}

Upvotes: 1

eyalm
eyalm

Reputation: 3366

Try this function:

isxdigit(c);

Upvotes: 0

Related Questions