What's Here?
- Members: 149,620
- Replies: 506,751
- Topics: 79,851
- Snippets: 2,666
- Tutorials: 706
- Total Online: 1,899
- Members: 66
- Guests: 1,833
|
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
|
|
Rating:

|
|
Views: 2,918 |
Language: C++
|
|
Last Modified: December 3, 2006 |
Snippet
#include<iostream>
char *BaseConversion(unsigned int , int );
int main() {
std::cout<<"Hexadecimal 'a' to Decimal : "<<BaseConversion(0xa,10)<<std::endl;
std::cout<<"Decimal '10' to Hexadecimal: "<<BaseConversion(10,16)<<std::endl;
std::cout<<"Hexadecimal 'a' to Octal : "<<BaseConversion(0xa,8)<<std::endl;
std::cout<<"Octal '12' to Hexadecimal : "<<BaseConversion(012,16)<<std::endl;
std::cout<<"Decimal '10' to Octal : "<<BaseConversion(10,8)<<std::endl;
std::cout<<"Octal '12' to Hexadecimal : "<<BaseConversion(012,16)<<std::endl;
return 0;
}
char *BaseConversion(unsigned int number, int base) {
static char buffer[50];
char *ptr=buffer;
//Checking for invalid base input
if(base < 2 || base > 16)
return NULL;
//Going to the end of buffer
ptr = &buffer[sizeof(buffer)-1];
*ptr = '\0';
//Actual Conversion
while(number != 0) {
*--ptr = "0123456789abcdef"[number % base];
number /= base;
}
return ptr;
}
Copy & Paste
|
|
|
Be Social
Reference Sheets
Bye Bye Ads
Monthly Drawing
Top Contributors
Top 10 Kudos This Month
|