[C++] Numeric Base Conversions Example

AceInfinity

Emeritus, Contributor
Joined
Feb 21, 2012
Posts
1,728
Location
Canada
Here's a nice little method to convert an integer to another base.
Code:
const char charArr[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
char* ConvertToBase(int num, int base)
{
	int len=0;
	int n = num;
	do len++; while((n/=base)!=0);
	int i = len;
	char* arr = new char[len+1];
	do{
		arr[--i]=charArr[num%base];
		num/=base;
	} while(num!=0);
	arr[len] = '\0';
	return arr;
}

Note: Because it takes an integer param, you'll have to convert any hex value for instance over to base 10 by some other means, but the expected num argument should already be in base 10 anyways to convert to another base.

Test with:
Code:
cout << ConvertToBase(255, 16) << endl;

Note: I know you can also use _itoa(), so I just posted this to show you how base conversion works.
 

Has Sysnative Forums helped you? Please consider donating to help us support the site!

Back
Top