将位数组转换为short

Convert bit array to short

本文关键字:short 转换 数组      更新时间:2023-10-16

我有一个函数,它返回short的位(灵感来自将整数转换为位表示):

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;
}

我该如何做相反的操作?转换短中的位数组?

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

CCD_ 1将CCD_ 2中的第i个比特设置为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;

本质上:

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

这假设bits指向具有至少sizeof(unsigned short)个元素的bool的阵列。我有没有测试它。可能有一个错误。但也许不是。