#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// To convert a-f or A-F to a decimal number
int chartoint(int c)
{
char hex[] = "aAbBcCdDeEfF";
int i;
int result = 0;
for(i = 0; result == 0 && hex[i] != '\0'; i++)
{
if(hex[i] == c)
{
result = 10 + (i / 2);
}
}
return result;
}
unsigned int htoi(const char s[])
{
unsigned int result = 0;
int i = 0;
int proper = 1;
int temp;
//To take care of 0x and 0X added before the hex no.
if(s[i] == '0')
{
++i;
if(s[i] == 'x' || s[i] == 'X')
{
++i;
}
}
while(proper && s[i] != '\0')
{
result = result * 16;
if(s[i] >= '0' && s[i] <= '9')
{
result = result + (s[i] - '0');
}
else
{
temp = chartoint(s[i]);
if(temp == 0)
{
proper = 0;
}
else
{
result = result + temp;
}
}
++i;
}
//If any character is not a proper hex no. , return 0
if(!proper)
{
result = 0;
}
return result;
}
int main(void)
{
char *endp = NULL;
char test[20];
printf("\nEnter a hexadecimal pattern : ");
scanf("%s",test);
if(htoi(test) == 0)
{
printf("\nEntered characters not proper Hexadecimal Number!!!\n");
exit(0);
}
printf("Hex : %s\tDecimal: %d\n" ,test, htoi(test));
}
Master programming effortlessly with Simplest Codings. From core algorithms and LLMs to clean code in Java, C++, and Python—get clear, bite-sized tutorials and practical developer guides for all skill levels.
Sunday, August 22, 2010
Hexadecimal to Integer Conversion in C
A simple implementation of converter which converts hexadecimal string to an integer.
Subscribe to:
Post Comments (Atom)
-
Overview of the SSL handshake Courtesy: http://www-01.ibm.com/support/knowledgecenter Steps involved in SSL handshake (Courtesy:...
-
To implement the kind of storage which stores strings as the search keys , there is a need to have special data structures which can store ...
-
A simple implementation of a packet sniffer in C on linux platform using the libpcap library. This packet sniffer currently sniffs IP , TCP ...
No comments:
Post a Comment
Please post your valuable suggestions