Hi Sinaru :-)
Since I don't know how familiar you are with stuff like this I have too ask:
You represent a negative binary number as a positive binary number prefixed with a '-'. Is that your own intentional design or because you do not know the real way to represent negative numbers?
mbulow
Junior Poster in Training
50 posts since Dec 2009
Reputation Points: 20
Solved Threads: 23
Here is a way to do it using metaprograming. That way you get the result before you
even start the program.
#include <iostream>
template<int binarySequence>
struct Binary{
enum{ result = Binary<binarySequence/10>::result << 1 | binarySequence % 10 };
};
template<>
struct Binary<0>{
enum{ result = 0 };
};
int main(){
using namespace std;
cout << Binary<1>::result << endl; // outputs 2^0
cout << Binary<10>::result << endl; // outputs 2^1
cout << Binary<100>::result << endl; // outputs 2^2
cout << Binary<1000>::result << endl; // outputs 2^3
cout << Binary<10000>::result << endl; // outputs 2^4
cout << Binary<10100>::result << endl; // outputs 20
}
I admit, that the formula used is not credited to me. Although the above works.
It does not have a error checking, for input that does not consists of 1's and 0's.
Isn't this so cool? You get the answer before you even run your program!
firstPerson
Senior Poster
3,923 posts since Dec 2008
Reputation Points: 841
Solved Threads: 608