0

I'm trying to convert a string of HEX to a single float value. The string is 4 bytes long. It was defined as:

String B = "";

It is a substring of a longer string:

B = input.substring(6,14);

This results in the string I am trying to convert in to a single float value.
Online I found following code:

float y = *(float*)&B;

This compiles without an error, but when I run the code it's always 0.000000. I'm guessing I can't use that function with a string. A typical string can be "bb319ba6" which should be -0.002710083. For that I'm using a IEEE 754 converter I found online.

I basically need to do the same conversion on the Arduino. I hope somebody can help me with that.

gre_gor
  • 6,669
  • 9
  • 47
  • 52
  • Question : why aren't you just entering your float values as such in the first place? – spectras Jun 15 '17 at 11:35
  • I see you've included the IEEE-754 tag. That specification is unambiguous in its definition of the layout of the matissa, exponent, and the bias used. You'll need to do some lengthy bitwise manipulations, but it can be done. Follow the specification. – TomServo Jun 15 '17 at 11:45
  • There is a Amplifier with an ADC for a force sensor connected to the Arduino. The input data im getting are single bytes that i then put in to one String. – LostInTechnology Jun 15 '17 at 11:47
  • `float y = *(float*)&B;` this line makes no sense. You're re-interpreting a `String*` as a `float*`. If you have 4 bytes `b1,b2,b2,b3`, (lsB to msB) then you can convolute them into a 32-bit integer by doing `b1 | (b2 << 8) | (b3 << 16) | (b4 << 24)`, then re-interpret it as a float. (https://stackoverflow.com/questions/3991478/building-a-32bit-float-out-of-its-4-composite-bytes-c, https://stackoverflow.com/questions/26310249/converting-4-raw-bytes-into-32-bit-floating-point) – Maximilian Gerhardt Jun 15 '17 at 14:06

1 Answers1

0

You really shouldn't use String on these limited-RAM Arduinos. It can cause weird errors and hangs after random amounts of time (more info here). Just use a character array to hold the characters received from the sensor. Here's some code that will work with either String or a char[]:

uint8_t fromHex( char c )
{
  if ((0 <= c) && (c <= '9'))
    return (c - '0');
  if ('A' <= c) && (c <= 'F'))
    return (c - 'A');
  if ('a' <= c) && (c <= 'f'))
    return (c - 'a');
  return 0; // not a hex digit
}

void foo()
{
  float    y;
  uint8_t *yPtr = (uint8_t *) &y; // a pointer the the 4 bytes of `y`

  for (uint8_t i=0; i<sizeof(y); i++) {
    *yptr   = fromHex( B[ 6+2*i ] ) << 4;
    *yptr++ = fromHex( B[ 6+2*i + 1] );
  }
    ...

It simply stores the 4 bytes into the float, since Arduino floats already use the IEEE 754 format. No need to decode the exponent, mantissa, etc.

slash-dev
  • 1,569
  • 2
  • 9
  • 9