浮点数和字节数组问题的C ++联合 [英] C++ Union of a Float and a Byte Array Issue

查看:104
本文介绍了浮点数和字节数组问题的C ++联合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用arduino(基于AVR平台),并且有一种方法可以将一个浮点数写入到EEPROM中.我必须将浮点数转换为字节数组才能与EEPROM交互.我有两个功能,如下所示:

I am working on an arduino (based off the AVR platform) and I have a method that takes in a float and writes it to EEPROM. I have to convert the float to a byte array to interact with EEPROM. I have two functions as follow:

void WriteFloatToEEPROM(int address, float value) {
    union {
        byte byteVal[4];
        float floatVal;
    } data;

    data.floatVal = value;

    for (int i = 0; i < 4; i++) {
        EEPROM.update(address + i, data.byteVal[i]);
    }   
}

float ReadFloatFromEEPROM(int address) {
    union {
        byte byteVal[4];
        float floatVal;
    } data;

    for (int i = 0; i < 4; i++) {
        uint8_t readValue = EEPROM.read(address + i);

        data.byteVal[i] = readValue;        
    }

    return data.floatVal;
}

当我打印出此结果时,我将获得以下示例:

When I print out the results of this I get the following as a few examples:

Read value at address 50 for float read 0
Read value at address 51 for float read 0
Read value at address 52 for float read 0
Read value at address 53 for float read 0
    Returned float val for address 50:0.00
Read value at address 90 for float read 0
Read value at address 91 for float read 0
Read value at address 92 for float read 0
Read value at address 93 for float read 160
    Returned float val for address 90:-0.00
Read value at address 130 for float read 44
Read value at address 131 for float read 113
Read value at address 132 for float read 61
Read value at address 133 for float read 138
    Returned float val for address 130:-0.00
Read value at address 170 for float read 0
Read value at address 171 for float read 0
Read value at address 172 for float read 0
Read value at address 173 for float read 0
    Returned float val for address 170:0.00

我使用工会错误/向后写入EEPROM是什么吗?另外,如果有人有更好的方法可以这样做,我也乐于提出建议.预先感谢

Am I using a union wrong/writing to EEPROM backwards or something? Also if anyone has a better way of doing this, I am open to suggestions. Thanks in advance

推荐答案

不读取并列的活动"字段是UB(未定义行为).

Reading not the "active" field of the union is UB (Undefined Behavior).

您必须使用memcpy:

void WriteFloatToEEPROM(int address, float value) {
    byte byteVal[sizeof(float)];
    memcpy(byteVal, &value, sizeof(float));

    for (int i = 0; i < sizeof(float); i++) {
        EEPROM.update(address + i, byteVal[i]);
    }   
}

float ReadFloatFromEEPROM(int address) {
    byte byteVal[sizeof(float)];

    for (int i = 0; i < sizeof(float); i++) {
        byteVal[i] = EEPROM.read(address + i);
    }

    float f;
    memcpy(&f, byteVal, sizeof(float));
    return f;
}

这篇关于浮点数和字节数组问题的C ++联合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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