# how can i interleave a section of two binary numbers?

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
``````