Char value to int directly

Hi everybody,

We have custom made sensor and it send char array data as below;

0x68 0x1F 0x00 0x84 0x10 0x50 0x45 0x01 0x10 0x28

0x68 start of frame
0x1F valid data
0x00 address
0x84 start of data
3 byte data 1
3 byte data 2

data 1 => 0x10 0x50 0x45 means -50.45
data 2 => 0x01 0x10 0x28 means +110.28

How can we read this value to a float?

I couldn't figure out how to read?

Thanks for your help.

Out of interest, what's the meaning of the data? Latitude and Longitude?
At any rate, your three bytes need to be processed piecewise.
1st byte has 2 parts, a sign and, from the looks of it, a single number from 0-9
Second byte, two BCD digits
Third byte, two BCD digits.
I'd start as follows:
1st Digit, AND with 0x0F, multiply by 100, store in result
2nd Digit, AND with 0xF0, shift right by 4 bits, multiply by 10, add to result
2nd Digit, AND with 0x0F, add to result
3rd Digit, AND with 0xF0, shift right by 4 bits, divide by 10, add to result
3rd Digit, AND with 0x0F, divide by 100, add to result
1st Digit, AND with 0x10, if not 0, multiply result by -1.
Be advised, there are probably faster ways, but this stepwise process is clear.
Go ahead and code this, come back with the result if it doesn't work.

1 Like

I would put the number together as an integer. That will minimize the risk of an integer-to-float conversion being a little bit off.

1 0x05045 -> 5045
0 0x11028 -> 11028

Then divide by 100.0:

1 0x05045 -> 5045 -> 50.45
0 0x11028 -> 11028 -> 110.28

Then apply the sign:

1 0x05045 -> 5045 -> 50.45 -> -50.45
0 0x11028 -> 11028 -> 110.28 -> 110.28

If the numbers might go over 327.67, store the number in an 'unsigned int' before the divide.

If the numbers might go over 655.35, store the number in a 'long int' before the divide.

@camsysca it worked very well. Thanks for your suggestion.
@johnwasser how to put all the value to a int value?

How are you reading the values?

I am reading all values to char array as char msg[]. after reading

if (msg[0] = 0x10)
  {
    neg = true;
  }
  int result2 = msg[0] & 0x0F;
  result2 = result2 * 100;

this is the code where I convert it to 1 byte of value which is percentile of value.

  // Put the number together as an integer.

  unsigned long number;

  number = msg[0] & 0x0F;
  number = (number * 10) + (msg[1] >> 4);
  number = (number * 10) + (msg[1] & 0x0F);
  number = (number * 10) + (msg[2] >> 4);
  number = (number * 10) + (msg[2] & 0x0F);
  number = (number * 10) + (msg[3] >> 4);
  number = (number * 10) + (msg[3] & 0x0F);

  // Then divide by 100.0:
  float value = number / 100.0;

  // Then apply the sign:
  if ((msg[0] >> 4) == 1)
    value = -value;

Thanks for your help.

perhaps you mean
if(msg[0] == 0x10)
The first statement is always true, the latter is a test if true.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.