Wednesday 10 November 2010

Number of bits to represent an arbitrary positive number X

Simple program to find the number of bits required to represent a positive number.



//This program is to find out the number of bits required to represent a positive integer
//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy

#include<iostream>
#include <cmath>

using namespace
std;

unsigned int
TraditionalApproach(const unsigned int& num)
{

if
(num)
{

return
(int)floor(log((double)num)/log(2.0) + 1.0);
}

return
1;
}


unsigned int
SimplifiedApproach(const unsigned int& num)
{

if
(num)
{

unsigned int
tempNum = num;
unsigned int
numOfBits = 0;
while
(tempNum)
{

numOfBits++;
tempNum >>= 1;
}

return
numOfBits;
}

return
1;
}



int
main()
{

//Finding number of bits the traditional way
cout<<"\n** Traditional Approach **\n";
cout<<"The number of bits required to represent 0 = "<<TraditionalApproach(0)<<endl;
cout<<"The number of bits required to represent 1 = "<<TraditionalApproach(1)<<endl;
cout<<"The number of bits required to represent 15 = "<<TraditionalApproach(15)<<endl;
cout<<"The number of bits required to represent 16 = "<<TraditionalApproach(16)<<endl;
cout<<"The number of bits required to represent 75 = "<<TraditionalApproach(75)<<endl;
cout<<"The number of bits required to represent 125 = "<<TraditionalApproach(125)<<endl;
cout<<"The number of bits required to represent 130 = "<<TraditionalApproach(130)<<endl;

cout<<"\n** Simplified Approach **\n";
cout<<"The number of bits required to represent 0 = "<<SimplifiedApproach(0)<<endl;
cout<<"The number of bits required to represent 1 = "<<SimplifiedApproach(1)<<endl;
cout<<"The number of bits required to represent 15 = "<<SimplifiedApproach(15)<<endl;
cout<<"The number of bits required to represent 16 = "<<SimplifiedApproach(16)<<endl;
cout<<"The number of bits required to represent 75 = "<<SimplifiedApproach(75)<<endl;
cout<<"The number of bits required to represent 125 = "<<SimplifiedApproach(125)<<endl;
cout<<"The number of bits required to represent 130 = "<<SimplifiedApproach(130)<<endl;

return
0;
}



The output is as follows:

No comments:

Post a Comment