将浮点数转换为4 uint8_t

Eva*_*eil 12 c++ casting type-conversion uint8t floating-point-conversion

我有一个需要通过CAN协议发送的float变量.为此,必须在4个uint8_t变量中切割32位的浮点数.

我完全不知道该怎么做.我首先考虑将float转换为int但我在Internet上找到的使用强制转换或联合的一些答案似乎不起作用.

这是我正在尝试做的一个简单示例:

float f;
uint8_t ut1,ut2,ut3,ut4;

//8 first bits of f into ut1
//8 second bits of f in ut2
...

// Then I can send the uint8_t through CAN
...
Run Code Online (Sandbox Code Playgroud)

谢谢.

doh*_*shi 7

通常通过将float转换为uint8_t数组来完成此操作.

在C中你可以这样做:

uint8_t *array;
array = (unit8_t*)(&f);
Run Code Online (Sandbox Code Playgroud)

在C++中使用reinterpret_cast

uint8_t *array;
array = reinterpret_cast<uint8_t*>(&f);
Run Code Online (Sandbox Code Playgroud)

那么array [0],...,array [3]就是你的字节.

  • 耐力怎么样? (2认同)
  • 我认为这个答案不应该被接受。转换为不相关的类型是 C++ 中的 UB,并且它也可能违反严格的别名规则。应按照下面答案中的建议使用 Union。在 c++20 中,您还可以使用 std::bit_cast 而不是 memcpy 方法。 (2认同)