设定long long型长度为8。

1 long long转字节数组

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

void LongLongToBytes(long long value, unsigned char* bytes)
{
    size_t length = sizeof(long 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);
    bytes[4] = (unsigned char)((0xff00000000 & value) >> 32);
    bytes[5] = (unsigned char)((0xff0000000000 & value) >> 40);
    bytes[6] = (unsigned char)((0xff000000000000 & value) >> 48);
    bytes[7] = (unsigned char)((0xff00000000000000 & value) >> 56);
}

2 字节数组转long long

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

long long BytesToLongLong(unsigned char* bytes)
{
    long long value = bytes[0] & 0xFF;
    value |= ((bytes[1] << 8) & 0xFF00);
    value |= ((bytes[2] << 16) & 0xFF0000);
    value |= ((bytes[3] << 24) & 0xFF000000);
    value |= ((((long long)bytes[4]) << 32) & 0xFF00000000);
    value |= ((((long long)bytes[5]) << 40) & 0xFF0000000000);
    value |= ((((long long)bytes[6]) << 48) & 0xFF000000000000);
    value |= ((((long long)bytes[7]) << 56) & 0xFF00000000000000);
    return value;
}

3 使用示例

#include <iostream>

void LongLongToBytes(long long value, unsigned char* bytes)
{
    // 位操作时 使用一个unsigned int变量来作为位容器。
    size_t length = sizeof(long 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);
    bytes[4] = (unsigned char)((0xff00000000 & value) >> 32);
    bytes[5] = (unsigned char)((0xff0000000000 & value) >> 40);
    bytes[6] = (unsigned char)((0xff000000000000 & value) >> 48);
    bytes[7] = (unsigned char)((0xff00000000000000 & value) >> 56);
}

long long BytesToLongLong(unsigned char* bytes)
{

    // 位操作时 使用一个unsigned int变量来作为位容器。
    long long value = bytes[0] & 0xFF;
    value |= ((bytes[1] << 8) & 0xFF00);
    value |= ((bytes[2] << 16) & 0xFF0000);
    value |= ((bytes[3] << 24) & 0xFF000000);
    value |= ((((long long)bytes[4]) << 32) & 0xFF00000000);
    value |= ((((long long)bytes[5]) << 40) & 0xFF0000000000);
    value |= ((((long long)bytes[6]) << 48) & 0xFF000000000000);
    value |= ((((long long)bytes[7]) << 56) & 0xFF00000000000000);
    return value;
}


int main()
{
    unsigned char longlongByteArray[8];
    long long a = 10;
    LongLongToBytes(a, longlongByteArray);

    std::cout << BytesToLongLong(longlongByteArray) << std::endl;

    return 0;
}