【问题标题】:What does the cast pointer do in this code?强制转换指针在这段代码中做了什么?
【发布时间】:2016-03-09 13:20:41
【问题描述】:

这个函数应该将一个整数值转换为十六进制的 32 位浮点表示。但我不明白第 3 行实际上是做什么的。任何人都可以详细说明吗?

void convert_to_IEEE754( int value, char* ieee754_str ) {
  float ieee754_value = (float) value / 1000;  // value is pre-multiplied by 1000
  byte* array = (byte*) &ieee754_value;
  sprintf( ieee754_str, "%02x%02x%02x%02x", array[3], array[2], array[1], array[0] );
}

【问题讨论】:

  • 第三行byte* array = (byte*) &ieee754_value;ieee754_value 占用的内存地址处的值转换为类型(byte*) 并将地址分配给array(之前在某处已声明为无符号-char 或类型定义)。这允许索引ieee754_value 中的 4 字节,然后通过sprintf 写入ieee754_str
  • byte 不是标准类型。为什么不使用unsigned char *
  • @DavidC.Rankin: "... is cast the values at the memory address used by ..." – 不。它将float的地址转换为byte *,而不是价值。
  • 你是指代码中的第 3 行还是函数中的第 3 行?
  • @Olaf 字节被使用我认为这是 Arduino 的标准类型之一:arduino.cc/en/Reference/Byte

标签: c pointers casting arduino


【解决方案1】:

这个演员表:

byte* array = (byte*) &ieee754_value;

将值&ieee754_value 转换为byte * 类型,以便可以将其分配给变量array。如果没有强制转换,表达式&ieee754_value 的类型为float *,并且这样的值不能分配给byte * 类型的变量。因此演员阵容是必要的。

然后使用array 指针读取构成值的字节。

这不是推荐的技术,最好使用union

union {
  float ieee754_value;
  byte  bytes[4];
} tmp = { .ieee754_value = (float) value / 1000 };

然后通过tmp.bytes访问字节。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-14
    • 1970-01-01
    • 2012-01-05
    • 2016-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多