I am trying to "merge" two binary integers into one but I can't seem to get it right.
The operation I am trying to do is:
Number of bits to merge = 3 (precomputed parameter)
Int 1 : 10010
Int 2 : 11011
Given these two numbers, append 3 bit of each to the result (left to right):
Result : 11 01 00.
Meaning the first bit of the first integer and the first bit of the second integer. Then the second bit of the first integer and the second bit of the secod integer... and so on "Number of bits to merge" times.
Another example with letters would be:
Number of bits to merge = 4
Int1: abcde
Int2: xyzwt
Result: ax by cz dw
My idea is to use a for loop with the ammount of bits I have to set and there append to the result number, but I don't know how to do that "appending".
You can set each bit in a loop:
std::uint32_t merge(std::size_t start, std::size_t numberOfBits, int i1, int i2) {
if (start == 0 || start > sizeof(int) * 8) return 0;
if (numberOfBits == 0 || numberOfBits > 16) return 0;
if (start < numberOfBits) return 0;
int result = 0;
for (std::size_t i = 0; i < numberOfBits; ++i) {
std::size_t srcPos = start - 1 - i;
std::size_t destPos = 2 * (numberOfBits - i) - 1;
result |= (i1 & (1 << srcPos)) >> srcPos << destPos;
result |= (i2 & (1 << srcPos)) >> srcPos << (destPos - 1);
}
return result;
}
int main() {
std::size_t start = 5;
std::size_t numberOfBits = 3;
int i1 = 0b10010;
int i2 = 0b11011;
return merge(start, numberOfBits, i1, i2);
}
i1 & (1 << (start - 1 - i))
reads the i-th bit from left. >> (start - 1 - i)
shifts it to the right. << (2 * (numberOfBits - i) - 1)
resp. << (2 * (numberOfBits - i) - 2)
shifts it to the correct position in the result.
Tested with input:
Start : 5
Number of bits : 3
Int 1 : 0b10010
Int 2 : 0b11011
output:
52 // == 0b110100
and input:
Start : 4
Number of bits : 2
Int 1 : 0b1010
Int 2 : 0b0101
output:
9 // == 0b1001