In: Computer Science
Write a program that copies the even number of bits from a into
the corresponding bits in b ,only use bit-manipulation
instructions, no loop
int main ()
{
uint_32 a = 0 xaabbccdd ;
uint_32 b = 0 x11223344 ;
// Replace bits 0 ,2 ,4 ,... of b with bits 0 ,2 ,4 ,... from a . uint_32 result = ...;
// Print out the result as a hexadecimal number
}
#include <bits/stdc++.h>
using namespace std;
//function to replace bits
unsigned int replaceBits(unsigned int x, unsigned int y)
{
// Getting all even bits of x
unsigned int even_bits = x & 0xAAAAAAAA;
// Getting all odd bits of y
unsigned int odd_bits = y & 0x55555555;
even_bits >>= 1; // Right shift will give even bits
odd_bits <<= 1; // Left shift will give odd bits
return (even_bits | odd_bits); // Combine even bits of x and odd
bits of y
}
// Driver code
int main()
{
unsigned int x = 0xaabbccdd;
unsigned int y = 0x11223344;
unsigned int num, temp, i = 1, j, r;
num = replaceBits(x,y); //stroing the decimal equivalent value
after Replacing bits 0 ,2 ,4 ,... of b with bits 0 ,2 ,4 ,... from
a
//below is the code to convert the decimal to hexadecimal
char hex[50];
temp = num;
while (temp != 0)
{
r = temp % 16;
if (r < 10)
hex[i++] = r + 48;
else
hex[i++] = r + 55;
temp = temp / 16;
}
cout << "\nHexadecimal equivalent of " << num <<
" is : "; //printing the hexadecimal value
for (j = i; j > 0; j--)
cout << hex[j];
return 0;
}
Please let me know if anything is required.