Code Snippets

  

C++ Source Code


Welcome to Dream.In.Code
Become a C++ Expert!

Join 149,620 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,899 people online right now. Registration is fast and FREE... Join Now!





Interchange between base 2 to 16

Following program converts the number from any base between 2-16 to any base between 2-16. Idea taken from C-FAQ by Steve Summit.

Submitted By: Xing
Actions:
Rating:
Views: 2,918

Language: C++

Last Modified: December 3, 2006

Snippet


  1. #include<iostream>
  2.  
  3. char *BaseConversion(unsigned int , int );
  4.  
  5. int main() {
  6.     std::cout<<"Hexadecimal 'a' to Decimal : "<<BaseConversion(0xa,10)<<std::endl;
  7.     std::cout<<"Decimal '10' to Hexadecimal: "<<BaseConversion(10,16)<<std::endl;
  8.     std::cout<<"Hexadecimal 'a' to Octal   : "<<BaseConversion(0xa,8)<<std::endl;
  9.     std::cout<<"Octal '12' to Hexadecimal  : "<<BaseConversion(012,16)<<std::endl;
  10.     std::cout<<"Decimal '10' to Octal      : "<<BaseConversion(10,8)<<std::endl;
  11.     std::cout<<"Octal '12' to Hexadecimal  : "<<BaseConversion(012,16)<<std::endl;
  12.     return 0;
  13. }
  14.  
  15. char *BaseConversion(unsigned int number, int base) {
  16.     static char buffer[50];
  17.     char *ptr=buffer;
  18.  
  19.      //Checking for invalid base input
  20.      if(base < 2 || base > 16)
  21.           return NULL;
  22.  
  23.      //Going to the end of buffer
  24.      ptr = &buffer[sizeof(buffer)-1];
  25.      *ptr = '\0';
  26.  
  27.      //Actual Conversion
  28.      while(number != 0) {
  29.           *--ptr = "0123456789abcdef"[number % base];
  30.           number /= base;
  31.      }
  32.      return ptr;
  33. }

Copy & Paste


Comments


There are currently no comments for this snippet. Be the first to comment!

Add comment


You must be registered and logged on to </dream.in.code> to leave comments.




Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month