memcpy vs 用于读取 BLE 传感器浮点数的指针转换
memcpy vs pointer cast for reading BLE sensor float
我遇到了两种读取 BLE 传感器浮点值的解决方案。 memcpy 方法简单明了,但我遇到的另一种方法对我来说不是很清楚。有人可以准确说明指针转换方法的工作原理吗?
// Represents data read from BLE device. Float value of 1.5
uint32_t data = 0x3fc00000;
float sensorValue;
// Memcpy method, makes sense and is straightforward
memcpy(&sensorValue, &data, sizeof(sensorValue));
// Works, but don't fully understand exactly how
sensorValue = *(float *)&data;
&data 是指向 uint32_t 的指针。因此,(float *)&data 将其转换为指向浮点数的指针。最后,*(float *)&data 取消引用该指针。
你可以做同样的事情:
uint32_t *ui32 = &data
float *f = (float *) ui32;
sensorValue = *f;
但是,确切的行为可能取决于平台。
我遇到了两种读取 BLE 传感器浮点值的解决方案。 memcpy 方法简单明了,但我遇到的另一种方法对我来说不是很清楚。有人可以准确说明指针转换方法的工作原理吗?
// Represents data read from BLE device. Float value of 1.5
uint32_t data = 0x3fc00000;
float sensorValue;
// Memcpy method, makes sense and is straightforward
memcpy(&sensorValue, &data, sizeof(sensorValue));
// Works, but don't fully understand exactly how
sensorValue = *(float *)&data;
&data 是指向 uint32_t 的指针。因此,(float *)&data 将其转换为指向浮点数的指针。最后,*(float *)&data 取消引用该指针。
你可以做同样的事情:
uint32_t *ui32 = &data
float *f = (float *) ui32;
sensorValue = *f;
但是,确切的行为可能取决于平台。