Sunday 22 June 2014

C++ program to toggle odd bits


Here is a C++ program to toggle odd bits


 SOURCE CODE OUTPUT
#include<iostream>
#include<math.h>
using namespace std;
void binary(int num)
{
    int a=num,k,y,amask;
    for(y=0;num>0;y++,num/=2);
    for(int i=y-1;i>=0;i--)
    {
        amask=1<<i;
        k=a&amask;
        k==0?cout<<"0":cout<<"1";
    }
}
void toggle(int num)
{
    int a=num,ebit=0,k,y,amask;
    for(y=0;num>0;y++,num/=2);
    for(int i=1;i<y;i+=2)
        ebit+=pow(2,i);
    a=a^ebit;
    binary(a);
}
int main()
{
    int a,n,ebit;
    cout<<"Enter the number : ";
    cin>>a;
    cout<<"Before Toggling odd bits : ";
    binary(a);
    cout<<endl<<"After Toggling odd bits : ";
    toggle(a);
    return 0;
}

Any questions regarding to program please write in comments.

No comments:

Post a Comment