设定float型字节长度为4字节。

1 float转字节数组

float型转字节数组byte[]或者unsigned char[]

void FloatTobytes(float data, unsigned char bytes[])
{
    size_t length = sizeof(float);

    unsigned char* pdata = (unsigned char*)&data; 
    for (int i = 0; i < length; i++)
    {
        bytes[i] = *pdata++;
    }
}

2 字节数组转float

字节数组byte[]或者unsigned char[]转float型

float BytesToFloat(unsigned char bytes[])
{
    return *((float*)bytes);
}

3 使用示例

#include <iostream>

float BytesToFloat(unsigned char bytes[])
{
    return *((float*)bytes);
}

void FloatTobytes(float data, unsigned char bytes[])
{
    size_t length = sizeof(float);

    unsigned char* pdata = (unsigned char*)&data; 
    for (int i = 0; i < length; i++)
    {
        bytes[i] = *pdata++;
    }
}


int main()
{
    unsigned char floatByteArray[4];
    float a = 10.0;
    FloatTobytes(a, floatByteArray);

    std::cout << BytesToFloat(floatByteArray) << std::endl;

    return 0;
}