0

I want to be able to retain the same amount of bits to my vector whilst still performing binary addition. For example.

int numOfBits = 4;
int myVecVal = 3;
vector< bool > myVec;
GetBinaryVector(&myVec,myVecVal, numOfBits);

and its output would be:

{0, 0, 1, 1}

I don't know how to make a function of GetBinaryVector though, any ideas?

  • Did you see https://stackoverflow.com/questions/7829854/how-to-store-a-bit-array-in-c? – Allan Wind Feb 14 '21 at 06:49
  • It needs to retain the same size bits though, not adjust them to the size of the value. Ie, a value of 30 will have a size of 5, no more no less. Or unless I specified its size, which I have, so I can also have a value of 30 but a size of 100 for example. @AllanWind –  Feb 14 '21 at 06:49
  • What should happen on overflow? – Allan Wind Feb 14 '21 at 07:02
  • Nothing, It can crash or it should just be all 1's, (unsigned integer). It really doesn't matter for my use case –  Feb 14 '21 at 07:04

1 Answers1

-1

This seems to work (although the article I added in initial comment seem to suggest you only have byte level access):

void GetBinaryVector(vector<bool> *v, int val, int bits) {
    v->resize(bits);
    for(int i = 0; i < bits; i++) {
        (*v)[bits - 1 - i] = (val >> i) & 0x1;
    }
}

The left hand side sets the i'th least significant bit which is index bits - 1 - i. The right hand side isolates the i'th least significant bit by bit shifting the value down i'th bit and masking everything but the least significant bit.

In your example val = 8, bits = 15. In the first iteration i = 0: we have (*v)[15 - 1 - 0] = (8 >> 0) & 0x1. 8 is binary 1000 and shifting it down 0 is 1000. 1000 & 0x1 is 0. Let's jump to i = 4: (*v)[15 - 1 - 4] = (8 >> 4) & 0x1. 1000 >> 4 is 1 and 1 & 0x1 is 1, so we set (*v)[10] = 1. The resulting vector is { 0, ..., 0, 1, 0, 0, 0 }

Allan Wind
  • 23,068
  • 5
  • 28
  • 38