Archived

This topic is now archived and is closed to further replies.

White Crow

Hex to integers

Recommended Posts

White Crow    122
Hi I had to write a function that convert a string of hexadecimal digits into it''s equivalent integers value. Now I do not know how that hexadecimal system works so I am asking if someone could explain ti to me or point me to a website or something. Whitecrow

Share this post


Link to post
Share on other sites
smart_idiot    1298
The easy way:

#include <stdio.h>

int main()
{
int var;
printf("Enter the number in hex: ");
scanf("%x", &var);
printf("The number in decimal is: %d\n", var);
}


An actual function:

// example, HexToDec("abc") will return 2748.


unsigned int HexToDec(const char *s)
{
unsigned int result = 0;

for(; *s ; ++s)
if(*s >= ''0'' && *s <= ''9'')
result = result*16+(*s-''0'');
else if(*s >= ''a'' && *s <= ''f'')
result = result*16+(*s-''a''+10);
else if(*s >= ''A'' && *s <= ''F'')
result = result*16+(*s-''A''+10);
else
break;

return result;
}

Share this post


Link to post
Share on other sites
SoulSkorpion    238
quote:
Original post by White Crow
Hi

I had to write a function that convert a string of hexadecimal digits into it''s equivalent integers value. Now I do not know how that hexadecimal system works so I am asking if someone could explain ti to me or point me to a website or something.

Whitecrow


There''s tons of information all over the internet, but I''m feeling charitable.

Hexadecimal is base 16. Decimal, our normal number system, is base 10.

Under base decimal, the number 5453 is really:
5x10^3 + 4x10^2 + 5x10^1 + 3x10^0

Under hexadecimal, it''s:
5x16^3 + 4x16^2 + 5x16^1 + 3x16^0

And since there are only 10 Arabic numerals (0123456789), to represent 10, 11, 12, 13, 14 and 15 as single digits the letters ABCDEF are used.

So the number 26 is 26 in decimal, and is 1A in hexadecimal.

Share this post


Link to post
Share on other sites