将位数组转换为short

时间:2013-12-06 22:35:31

标签: c++ byte bit short

我有一个函数可以返回一个短的位(灵感来自Converting integer to a bit representation):

bool* bitsToShort(short value) {
    bool* bits = new bool[15];
    int count = 0;
    while(value) {
        if (value&1)
            bits[count] = 1;
        else
            bits[count] = 0;
        value>>=1;
        count++;
    }
    return bits;
}

我该如何反过来?转换短路中的位数组?

3 个答案:

答案 0 :(得分:1)

short shortFromBits(bool* bits) {
    short res = 0;
    for (int i = 0; i < 15; ++i) {
        if (bits[i]) {
            res |= 1 << i;
        }
    }
    return res;
}

res |= (1<<i)res中的第i位设置为1。

答案 1 :(得分:1)

像这样:

bool* bits = ... // some bits here
short res = 0;
for (int i = 14 ; i >= 0 ; i--) {
    res <<= 1;             // Shift left unconditionally
    if (bits[i]) res |= 1; // OR in a 1 into LSB when bits[i] is set
}
return res;

答案 2 :(得分:-1)

本质:

unsigned short value = 0;
for (int i = sizeof(unsigned short) * CHAR_BIT - 1; 0 <= i; --i) {
    value *= 2;
    if (bits[i)
        ++value;
}

这假设bits指向bool的数组,且至少包含sizeof(unsigned short)个元素。我有测试它。某处可能存在一个错误的错误。但也许不是。