user3055473
user3055473

Reputation: 13

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?

Upvotes: 0

Views: 2401

Answers (3)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726639

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;

Upvotes: 1

Pete Becker
Pete Becker

Reputation: 76360

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. I have not tested it. There could be an off-by-one error somewhere. But maybe not.

Upvotes: -1

Ivan Smirnov
Ivan Smirnov

Reputation: 4435

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.

Upvotes: 2

Related Questions