Arduino字符串浮动

时间:2017-06-15 11:31:48

标签: string arduino floating-point ieee-754

我正在尝试将一串HEX转换为单个浮点值。该字符串长度为4个字节。它被定义为:

String B = "";

它是较长字符串的子字符串:

B = input.substring(6,14);

这会导致我尝试将字符串转换为单个浮点值 在线我发现以下代码:

float y = *(float*)&B;

这编译时没有错误,但是当我运行代码时,它总是0.000000。我猜我不能用字符串来使用该函数。典型字符串可以是"bb319ba6",应该是-0.002710083。为此我在网上找到了IEEE 754转换器。

我基本上需要对Arduino进行相同的转换。我希望有人可以帮助我。

1 个答案:

答案 0 :(得分:0)

你真的不应该在这些有限的RAM Arduinos上使用String。它会导致奇怪的错误并在随机时间后挂起(更多信息here)。只需使用字符数组来保存从传感器接收的字符。以下是一些适用于Stringchar[]的代码:

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] );
  }
    ...

它只是将4个字节存储到float,因为Arduino floats已经使用IEEE 754格式。无需解码指数,尾数等。