设定long型长度为4字节。

1 long转字节数组

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

void LongToBytes(long value, unsigned char* bytes)
{
    size_t length = sizeof(long);
    memset(bytes, 0, sizeof(unsigned char) * length);
    bytes[0] = (unsigned char)(0xff & value);
    bytes[1] = (unsigned char)((0xff00 & value) >> 8);
    bytes[2] = (unsigned char)((0xff0000 & value) >> 16);
    bytes[3] = (unsigned char)((0xff000000 & value) >> 24);
}

2 字节数组转long

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

long BytesToLong(unsigned char* bytes)
{
    long value = bytes[0] & 0xFF;
    value |= ((bytes[1] << 8) & 0xFF00);
    value |= ((bytes[2] << 16) & 0xFF0000);
    value |= ((bytes[3] << 24) & 0xFF000000);
    return value;
}

3 使用示例

#include <iostream>

void LongToBytes(long value, unsigned char* bytes)
{
    size_t length = sizeof(long);
    memset(bytes, 0, sizeof(unsigned char) * length);
    bytes[0] = (unsigned char)(0xff & value);
    bytes[1] = (unsigned char)((0xff00 & value) >> 8);
    bytes[2] = (unsigned char)((0xff0000 & value) >> 16);
    bytes[3] = (unsigned char)((0xff000000 & value) >> 24);
}

long BytesToLong(unsigned char* bytes)
{
    long value = bytes[0] & 0xFF;
    value |= ((bytes[1] << 8) & 0xFF00);
    value |= ((bytes[2] << 16) & 0xFF0000);
    value |= ((bytes[3] << 24) & 0xFF000000);
    return value;
}


int main()
{
    unsigned char longByteArray[4];
    long a = 10;
    LongToBytes(a, longByteArray);

    std::cout << BytesToLong(longByteArray) << std::endl;

    return 0;
}