设定long double型的字节长度为12。

1 long double转字节数组

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

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

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

2 字节数组转long double

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

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

3 使用示例

#include <iostream>

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

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

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


int main()
{
    unsigned char longDoubleByteArray[12];
    long double a = 15313132123.0;
    LongDoubleTobytes(a, longDoubleByteArray);

    std::cout << BytesToLongDouble(longDoubleByteArray) << std::endl;

    return 0;
}