In: Computer Science
I'm trying to convert between different number representations in C++ , I have the prototype but im not sure what do do from here
bool convertU(unsigned & n, const string & bits);
bits should have size exactly 5, and each char of bits should be '0' or '1'; otherwise
return false.
If bits is ok, set n to the number that bits represents as an unsigned and return true.
For example, convertU(n, "0101") and convertU(n, "10210") should return false;
convertU(n, "10011") should set n to 19 and return true.
If you have any doubts, please give me comment...
#include<iostream>
#include<cmath>
#include<string>
using namespace std;
bool convertU(unsigned & n, const string & bits);
int main(){
unsigned n;
if(convertU(n, "0101"))
cout<<"n = "<<n<<endl;
if(convertU(n, "10210"))
cout<<"n = "<<n<<endl;
if(convertU(n, "10011"))
cout<<"n = "<<n<<endl;
return 0;
}
bool convertU(unsigned & n, const string & bits){
n = 0;
int len = bits.size();
for(int i=0; i<bits.size(); i++){
if(bits[i]!='0' && bits[i]!='1')
return false;
if(bits[i]=='1')
n += pow(2, len-i-1);
}
return true;
}