In: Computer Science
MIPS
Write a program that asks the user to enter an unsigned number and read it. Then swap the bits at odd positions with those at even positions and display the resulting number. For example, if the user enters the number 9, which has binary representation of 1001, then bit 0 is swapped
with bit 1, and bit 2 is swapped with bit 3, resulting in the binary number 0110. Thus, the
program should display 6.
Since the language of the program is not mentioned, I have used C++
Code :-
#include<bits/stdc++.h>
using namespace std;
int main(){
int number;
cin>>number;
vector<int>bitVector;
int tempNumber=number;
while(tempNumber){
//Filling the Bit
Vector
bitVector.push_back(tempNumber&1);
tempNumber>>=1;
}
reverse(bitVector.begin(),bitVector.end());
//Swapping the bits
for(int i=0;i<bitVector.size()-1;i+=2){
swap(bitVector[i],bitVector[i+1]);
}
/*
//Displaying the modified BitVector
for(int i=0;i<bitVector.size();i++){
cout<<bitVector[i];
}
cout<<"\n";
*/
reverse(bitVector.begin(),bitVector.end());
int Answer=0;
//Constructing the answer
for(int i=0;i<bitVector.size();i++){
if(bitVector[i]){
Answer|=(1<<i);
}
}
cout<<Answer<<"\n";
}
Screenshot for better understanding of the indentation
