简体   繁体   中英

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

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
}

试试这个功能:

isxdigit(c);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM