Integer in binary representation

#include <iostream>
#include <list>
using namespace std;
void print(const list<int>& li){
	list<int>::const_iterator it;
	short countT(0);
	for(it=li.begin();it!=li.end();++it){
		cout<<*it;
		countT++;
		if (!(countT%4)) cout<<" ";
	}
	cout<<endl;
}
list<int> PoDeToBi(int num){
	list<int> result(16,0);
	list<int>::reverse_iterator rit(result.rbegin());
	while (num!=0 && rit!=result.rend()){
		*rit=num%2;
		num/=2;
		++rit;
	}
	return result;
}
list<int> SumOfBi(const list<int> B1,const list<int> B2){
	list<int> result(16,0);
	list<int>::const_reverse_iterator crit1(B1.rbegin());
	list<int>::const_reverse_iterator crit2(B2.rbegin());
	list<int>::reverse_iterator ritR(result.rbegin());
	int remT(0);
	while (crit1!=B1.rend() && crit2!=B2.rend() && ritR!=result.rend()){
		if (remT+*crit1+*crit2<=1){
			*ritR=*crit1+*crit2+remT;
			remT=0;
		}
		else {
			*ritR=remT+*crit1+*crit2-2;
			remT=1;
		}
		crit1++;
		crit2++;
		ritR++;
	}
	return result;
}
list<int> NeDeToBi(int num){
	list<int> result(16,0);
	result=PoDeToBi(-num);
	list<int>::iterator it;
	for(it=result.begin();it!=result.end();++it){
		if (*it==0) *it=1;
		else *it=0;
	}
	result=SumOfBi(result,PoDeToBi(1));
	return result;
}
int BiToDe(const list<int>& Bi){
	int sum=0;
	list<int>::const_iterator it(Bi.begin());
	if (*it==0){
		it++;
		while(it!=Bi.end()){
			sum=sum*2+*it;
			++it;
		}
		return sum;
	}else{
		list<int> BiT(Bi);
		list<int>::iterator itT;
		for(itT=BiT.begin();itT!=BiT.end();++itT){
			if (*itT==0) *itT=1;
			else *itT=0;
		}
		itT=BiT.begin(); itT++;
		while(itT!=BiT.end()){
			sum=sum*2+*itT;
			++itT;
		}
		return -(sum+1);
	}
}
int main(){
	int a(23),b(15),c(-100);;
	list<int> la,lb,lc;
	la=PoDeToBi(a);
	lb=PoDeToBi(b);
	lc=NeDeToBi(c);
	print(la);print(lb);print(lc);
	cout<<BiToDe(la)<<endl;
	cout<<BiToDe(lb)<<endl;
	cout<<BiToDe(lc)<<endl;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s