简体   繁体   English

转换位数组为short

[英]Convert bit array to short

I have a function that returns the bits of a short (inspired from 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;
}

How can I do the reverse? 我该如何做相反的事情? Converte the array of bits in the short? 简而言之转换位数组?

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) sets the i-th bit in res to one. res |= (1<<i)res的第i位设置为1。

Like this: 像这样:

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;

Essentially: 实质上:

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

This assumes that bits points to an array of bool with at least sizeof(unsigned short) elements. 假设bits指向至少具有sizeof(unsigned short)元素的bool数组。 I have not tested it. 我还没有测试。 There could be an off-by-one error somewhere. 某个地方可能存在一个错误的错误。 But maybe not. 但也许不是。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM