c++实现整型和字节数组间的转化

整型转换到字节数组

在网络传输中经常需要将整型数字转换成字节数组,然后将字节数组发送到客户端,在c++,int是4个字节,long是8个字节。废话不说,代码如下(byte类型是uchar):
int32_t bytesto_int4(byte *bytes)
{
    //turn bytes array to integer
    int32_t num = bytes[0] & 0xFF;
    num |= ((bytes[1] << 8) & 0xFF00);
    num |= ((bytes[2] << 16) & 0xFF0000);
    num |= ((bytes[3] << 24) & 0xFF000000);
    return num;
}

字节数组到整型

void int4to_bytes(int32_t num, byte *bytes /*in array size must be 4*/)
{
    //turn integer to bytes array
    bytes[0] = num;
    bytes[1] = num >> 8;
    bytes[2] = num >> 16;
    bytes[3] = num >> 24;
}

扩展(长整型到字节数组)

void int8to_bytes(int64_t num, byte *bytes /*in array size must be 8*/)
{
    bytes[0] = num;
    bytes[1] = num >> 8;
    bytes[2] = num >> 16;
    bytes[3] = num >> 24;
    bytes[4] = num >> 32;
    bytes[5] = num >> 40;
    bytes[6] = num >> 48;
    bytes[7] = num >> 56;
}

字节数组到长整型

int64_t bytesto_int8(byte *bytes /*size must be 8*/)
{
    //turn bytes array to integer
    int64_t num = bytes[0] & 0xFF;
    num |= (((int64_t)bytes[1] << 8) & 0xFF00);
    num |= (((int64_t)bytes[2] << 16) & 0xFF0000);
    num |= (((int64_t)bytes[3] << 24) & 0xFF000000);
    num |= (((int64_t)bytes[4] << 32) & 0xFF00000000);
    num |= (((int64_t)bytes[5] << 40) & 0xFF0000000000);
    num |= (((int64_t)bytes[6] << 48) & 0xFF000000000000);
    num |= (((int64_t)bytes[7] << 56) & 0xFF00000000000000);
    return num;
}

你可能感兴趣的:(c/c++基础操作)