简体   繁体   中英

c function to convert hexadecimal to decimal representstion

I am using below function to convert hexadecimal to decimal but it's not printing the correct result. Can anyone help me with this?? Thanku..

#include<stdio.h>
#include<stdlib.h>
long hextoint(char hex)
{
printf("%x\n",hex);
long hexa=0;
int byte;
for(byte=0;byte<8;byte++)
{
    if(hex & (0x0001<<byte)) 
    {
        hexa+=1*(2^byte);
    }

    else
    {       
        hexa+=(0*(2^byte));
    }
}

return hexa;
}
int  main()
{
char content[]={0x1F,0xF2,0x24};
int i;
for(i=0;i<3;i++)
{
    long dec=hextoint(content[i]);
    printf("%ld\n",dec);
}
}

The problem you have is that you are mistaking presentation of values, and storage of values. All values in a computer is stored in binary format. But how you present it can be done differently (hexadecimal, decimal, octal etc.).

The values in the array content are hexadecimal only in the editor . Once compiled and stored in memory, it's all binary. So you don't need any special function to convert the values, just print them in decimal:

printf("%u\n", content[i]);

you do not need this function

you can print all your char array elements directely as decimal with:

for(i=0;i<3;i++)
{
    printf("%ld\n",content[i]);
}

A char value is just a numeric value stored as a binary in the computer. If you want to convert it to hex or decimal that's just a representation of the same value so the function hextoint doesn't really make sense and only has a meaning if you output it.

What you probably mean is to output a string which can be either in decimal or hex and for this you can use the printf family functions as you already did in your example code.

update

Reading your comment, your real issue seem to be with float/double and int , but this is independent of the representation as hex or decimal.

If you want to ie do some calculation like 23/100 and you want to get 0.23 as a result, then you must use float or double variables. In your example you use char which can only represent natural numbers between 0-255 if unsigned or -127 to 128 if signed.

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