Bitwise Manipulation Using C++
/*Write a function to determine the number of bits you would need to flip to convert from integer A to integer B
Input : 29 (11101) & 15 (01111)
Output: 2*/
# include<iostream>
using namespace std;
int main()
{
int a,b,c[5],d[5],count,i, bits;
a=29;
b=15;
count=0;
bits=0;
while((a>0) || (b>0))
{
c[count]=a%2;
d[count]=b%2;
a=a/2;
b=b/2;
count=count+1;
if (((a==0) || (a==1)) && ((b==0) || (b==1)))
{
c[count]=a;
d[count]=b;
break;
}
}
cout<<"binary of A ";
for(i=count;i>=0;i--)
{cout<<c[i]; // *(c+0)
}
cout<<"\nbinary of B ";
for(i=count;i>=0;i--)
{cout<<d[i]; }
for(i=count;i>=0;i--)
{
if (c[i]^d[i]==1)
{ bits=bits+1;}
}
cout<<"\nNumber of bits required to flip A to B is "<<bits;
return 0;
}
Input : 29 (11101) & 15 (01111)
Output: 2*/
# include<iostream>
using namespace std;
int main()
{
int a,b,c[5],d[5],count,i, bits;
a=29;
b=15;
count=0;
bits=0;
while((a>0) || (b>0))
{
c[count]=a%2;
d[count]=b%2;
a=a/2;
b=b/2;
count=count+1;
if (((a==0) || (a==1)) && ((b==0) || (b==1)))
{
c[count]=a;
d[count]=b;
break;
}
}
cout<<"binary of A ";
for(i=count;i>=0;i--)
{cout<<c[i]; // *(c+0)
}
cout<<"\nbinary of B ";
for(i=count;i>=0;i--)
{cout<<d[i]; }
for(i=count;i>=0;i--)
{
if (c[i]^d[i]==1)
{ bits=bits+1;}
}
cout<<"\nNumber of bits required to flip A to B is "<<bits;
return 0;
}
Comments
Post a Comment