# Answer to Question #5292 in C++ for aimelawan

Question #5292

5. Write a C++ program that can interleave bits of two entered 16 bit variable and stores the result in a 32 bit variable. For example, if user provides x and y, then the resulting number has bits of x at even position and bits of y at odd position. You will have to explore bitwise operators for the purpose

Expert's answer

#include "stdafx.h"

#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])

{

int x, y, r;

r = 0;

cin >> x;

cin >> y;

for(int i = 15; i >= 0; i--){

int t = 1;

t = t << i;

r = r << 1;

t = t & y;

t = t >> i;

r += t;

r = r << 1;

t = 1;

t = t << i;

t = t & x;

t = t >> i;

r += t;

}

return 0;

}

#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])

{

int x, y, r;

r = 0;

cin >> x;

cin >> y;

for(int i = 15; i >= 0; i--){

int t = 1;

t = t << i;

r = r << 1;

t = t & y;

t = t >> i;

r += t;

r = r << 1;

t = 1;

t = t << i;

t = t & x;

t = t >> i;

r += t;

}

return 0;

}

## Comments

## Leave a comment