Converts a string of hexadecimal digits into its equivalent integer value - C Data Type

C examples for Data Type:int

Description

Converts a string of hexadecimal digits into its equivalent integer value

Demo Code

#include <stdio.h>

#define MAXLINE 1000/*from   w w  w  . ja v  a  2 s  .  c o  m*/

long htoi(char s[]);

int main(void) {
   int len;
   char line[MAXLINE] = "0Xdead1234";

   printf("%lu\n", htoi(line));

   return 0;
}
long htoi(char s[])
{
   long n = 0;
   int c;

   for (int i = 0; s[i] != '\0'; ++i) {
      c = s[i];
      if (i == 0 && c == '0' && (s[1] == 'x' || s[1] == 'X')) {
         i = 1;
         continue;
      }
   }
   n *= 16;
   if (c >= '0' && c <= '9')
      n += c - '0';
   else if (c >= 'a' && c <= 'f')
      n += c - 'a';
   else if (c >= 'A' && c <= 'F')
      n += c - 'A';

   return n;
}

Result


Related Tutorials