Friday, June 22, 2007

Covert Decimal to Octal In C++

This snippet has a will convert Decimal number to Octal number.
// coverts decimal to ocal
// vishesh
// 21/05/2005

#include 

char* DEC_OCT(int);

int main()
{
 //
 int num;
 std::cout << "Enter a number: ";
 std::cin   >> num;
 std::cout << DEC_OCT(num);
 std::cin.get();
 return 0;
}

char* DEC_OCT(int dec)
{
 using namespace std;

 char *rtn;

 int prev, len, temp, *OCT;
 
 prev = dec;
 
 for(int i=0;prev!=0;i++)
 { 
  prev = prev/8;
  len=i;
 }

 OCT = new int[len+1];

 prev = dec;

 for(int i=0;prev!=0;i++)
 {
  OCT[i] = prev%8;
  prev = prev/8;
  len=i;
 }

 OCT[len+1] = prev%8;
 len++;

 for(int i=0;i<len/2;i++)
 {
  temp=OCT[i];
  OCT[i]=OCT[len-1-i];
  OCT[len-1-i]=temp;
 }

 rtn = new char[len+1];
 
 for(int i=0;i<len;i++)
 {
  rtn[i]=OCT[i]+'0';
  rtn[i+1]='\0';
 }
 
 return rtn;
}
 
Blogger Template Layout Design by [ METAMUSE ] : Code Name Gadget 1.1 Power By freecode-frecode.blogger.com & blogger.com Programming Blogs - BlogCatalog Blog Directory