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 }