设定double型字节长度为8。

1 double转字节数组

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

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

    char* p = (char*)&data;

    for (int i = 0; i < length; i++)
    {
        bytes[i] = *p++;
    }
}

2 字节数组转double

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

double BytesToDouble(unsigned char bytes[])
{
    double data = *((double*)bytes);
    return data;
}

3 使用示例

#include <iostream>

double BytesToDouble(unsigned char bytes[])
{
    double data = *((double*)bytes);
    return data;
}

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

    char* p = (char*)&data;

    for (int i = 0; i < length; i++)
    {
        bytes[i] = *p++;
    }
}


int main()
{
    unsigned char doubleByteArray[8];
    double a = 10.0;
    DoubleTobytes(a, doubleByteArray);

    std::cout << BytesToDouble(doubleByteArray) << std::endl;

    return 0;
}