设定short型长度为2。

1 short转字节数组

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

void ShortToBytes(short value, unsigned char* bytes)
{
    size_t length = sizeof(short);
    memset(bytes, 0, sizeof(unsigned char) * length);
    bytes[0] = (unsigned char)(0xff & value);
    bytes[1] = (unsigned char)((0xff00 & value) >> 8);
    return;
}

2 字节数组转short

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

short BytesToShort(unsigned char* bytes)
{
    short value = bytes[0] & 0xFF;
    value |= ((bytes[1] << 8) & 0xFF00);
    return value;
}

3 使用示例

#include <iostream>

void ShortToBytes(short value, unsigned char* bytes)
{
    size_t length = sizeof(short);
    memset(bytes, 0, sizeof(unsigned char) * length);
    bytes[0] = (unsigned char)(0xff & value);
    bytes[1] = (unsigned char)((0xff00 & value) >> 8);
    return;
}

short BytesToShort(unsigned char* bytes)
{
    short value = bytes[0] & 0xFF;
    value |= ((bytes[1] << 8) & 0xFF00);
    return value;
}


int main()
{
    unsigned char shortByteArray[2];
    short a = 10;
    ShortToBytes(a, shortByteArray);

    std::cout << BytesToShort(shortByteArray) << std::endl;

    return 0;
}