Search code examples
cembeddediar

i want to convert the data from long to ASCII in IAR workbench compiler


I am trying to convert the data from long to ASCII in iar, but i am not getting the result

My expected output as long value as 459150 i am getting the hex value after reversing the bytes i am getting the output as 0007018E after i am converting into ASCII i am getting the wrong output

i tried all conversion over here.

long convertToLong(char* data,const int len)
{
    UINT8 hex[8]={0};
    bool ret = ConvertToBCD((unsigned char*)data,len,hex);
    sendtoUSB("con to BCD",10);
    sendtoUSB(hex,len*2);
    return hextol(hex,len*2);
}

long hextol(char hexvalue[],int len)
{
    long result=0;
    int i=0;
    while (i<len)
    {
        result = result * 16;
        if(hexvalue[i] >= '0' && hexvalue[i] <= '9')
        {
            result = result + (hexvalue[i] - '0');
        }
        else if(hexvalue[i]>= 'a'&& hexvalue[i]<='f')
        {
            result= result+ (hexvalue[i]- 'a'+10);
        }
        else if(hexvalue[i]>= 'A'&& hexvalue[i]<='F')
        {
            result= result+ (hexvalue[i]- 'A'+10);
        }
        else
        {
            result=0;
            return result;
        }
        ++i;
    }
    return result;
}

void ltoa(long value,char buf[])
{
    int i=0,j=1;
    int temp=0;
    while(value !=0)
    {
        temp=value%10;
        buf[i++]=temp+0x30;
        value /=10;
    }
    reverse_byte(buf,4);
}

Solution

  • Try this-

    long int var = 0x0007018E;
    char buf[100];
    
    snprintf(buf,100,"%ld",var); //what variable having your hex value,pass it instead of var
    
    printf("%s \n",buf);