Haluna
Haluna

Reputation: 1

How to convert a message's value from hexadecimal to decimal?

I need to write a function that converts a message's byte (this.byte(2)) from hexadecimal to decimal, from a message I receive on the CAN bus. For example i have the following message on the CAN bus "F1 02 1A 13 00 00 00 00" The function should then returns the value 26 for this.byte(2) "1A".

I followed some examples found on the internet but I still don't get the right value. What is then wrong with my function ?

variables
{
  char hexa[2];
  long decimal, place;
  int val, len;
}

int HexToDec(char hexa[])
{   
  decimal = 0;
  i=0;
  place = 1;

  len = strlen(hexa);
  len--;

  for(i=0; hexa[i]!='\0'; i++)
  {
 
      if(hexa[i]>='0' && hexa[i]<='9')
      {
          val = hexa[i] - 48;
      }
      else if(hexa[i]>='a' && hexa[i]<='f')
      {
          val = hexa[i] - 97 + 10;
      }
        else if(hexa[i]>='A' && hexa[i]<='F')
        {
            val = hexa[i] - 65 + 10;
        }

        decimal += val * _pow(16, len);
        len--;
    }

    write("Hexadecimal number = %s\n", hexa);
    write("Decimal number = %lld", decimal);

    return 0;
}

on message *
{
  HexToDec(this.BYTE(2));  // for example 1A in hexadecimal
}

Upvotes: 0

Views: 2899

Answers (1)

Shyam
Shyam

Reputation: 682

Your requirement "convert hex to decimal" is a wrong statement. Because both Hexadecimal and Decimal are numbers. Your function HexToDec is taking string as input and not a number.
If you want to print this.BYTE(2) as a decimal value, you just have to write

write("Hex - %X", this.BYTE(2));
write("Dec - %d", this.BYTE(2));

Upvotes: 1

Related Questions