memcpy vs指针转换为读取BLE传感器浮点 [英] memcpy vs pointer cast for reading BLE sensor float

查看:80
本文介绍了memcpy vs指针转换为读取BLE传感器浮点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了两种解决方案,用于读取BLE传感器的浮点值.memcpy方法很简单并且很有意义,但是我遇到的另一种方法对我来说却不是很清楚.有人可以确切说明指针转换方法的工作原理吗?

I came across two solutions for reading the float value of a BLE sensor. The memcpy method is straightforward and makes sense, however the other method I came across is not very clear to me. Can someone clarify exactly how the pointer casting method works?

    // 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的指针.最后,*(float *)& data取消引用该指针.

&data is a pointer to a uint32_t. So, (float *)&data casts it as a pointer to a float. Finally, *(float *)&data dereferences that pointer.

您可以执行以下操作:

uint32_t *ui32 = &data
float *f = (float *) ui32;
sensorValue = *f;

但是,确切的行为可能取决于平台.

But, the exact behavior is likely to be platform dependent.

这篇关于memcpy vs指针转换为读取BLE传感器浮点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆