Contents  Computer science > Base conversion in c++ 
 

This is the full source code for some base conversion functions I wrote a while back. Feel free to use them, but if you do then I would appreciate an email just so I know someone found them useful :) You should be able to just copy and paste this code without modification. Don't worry about the text wrapping on this page, it should come out right in your editor...

/*
Base conversion functions
Written by Matt Squire, copyright 2004
This code may be used freely in any project but I can't guarantee that there aren't any bugs
(If you use this then no credit to the creator is required, but I would appreciate an email)

How it works:

Example 1: Converting 20 (dec) to binary...
20/2 =  10  (+  remainder 0)
10/2 =  5   (+  remainder 0)
5/2  =  2   (+  remainder 1)
2/2  =  1   (+  remainder 0)
1/2  =  0   (+  remainder 1)

The complete number (00101) needs to be reversed, so it equals 10100

Example 2: Converting 4C9 (hex - base 16) to decimal
First, find the place value and face value of each digit:

Digit      : 4   C  9
Face value : 4   12 9   (..note: Hex C means 12. A=10,B=11,C=12,D=13,E=14,F=15)
Place value: 256 16 1

Then multiply each face value by its place value and add all together:

(256*4)+(16*12)+9 = 1024+192+9 = 1225
Therefore, 4C9h = 1225d

http://www.insidereality.net
*/

#include "stdafx.h"
#include <iostream.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

//Declarations:
//Takes a decimal number, converts it to base and stores the result in szString. Returns 1 on success or 0 on failure
int DecToBase(int,long,char*);
//Takes a number in any base and converts it to decimal. 
//Number is a pointer to a string containing the value to convert (a string to allow for A-Z).
//Base is the base that number is in (e.g.16, if it is Hex)
int BaseToDec(char*,int);
//Returns position of a character in a string
int GetIndex(char *,char);

//Symbols used to display a number correctly
//Numbers over base 10 use letters to represent values over and equal to 10
//You should be able to increase the max no. of bases by adding other symbols
//Remember a string needs 1 extra space for null character
char symbols[37] = "0123456789ABCDEFGHIJKLMNoPQRSTUVWXYZ";
const int MAX_BASE = 36; //Highest base allowed (make sure there are enough symbols first!)
//

int main(int argc, char* argv[])
{
	char number[256] = "";
	cout << "Base conversion functions. Written by Matt Squire\n\n";
	//DecToBase samples
	cout << "Examples...\n\n";
	DecToBase(2,10,number);
	cout << "10dec to binary (base 2): " << number << endl;
	DecToBase(8,25,number);
	cout << "25dec to octal (base 8): " << number << endl;
	DecToBase(3,49,number);	
	cout << "240dec to base 36 (hexatridecimal?): " << number << endl;
	DecToBase(16,28,number);
	cout << "28dec to hexadecimal (base 16): " << number << endl ;
	//I don't know why I wasted time working this one out... but 998453 spells LEET in base 36
	DecToBase(36,998453,number);
	cout << "998453dec to base 36: " << number << endl << endl;
	//BaseToDec samples
	cout << "4C9hex to decimal: " << BaseToDec("4C9",16) << endl;
	cout << "1760octal to decimal: " << BaseToDec("1760",8) << endl;
	cout << "1101011101bin to decimal: " << BaseToDec("1101011101",2) << endl << endl;
	//User input sample
	int iInput = 0,iBase = 2, iSrcBase = 10;
	cout << "Try another conversion...\nEnter a number in any base between 2 and 36 (must be integer): ";
	cin >> number;
	cout << "Enter a base to convert from: ";
	cin >> iSrcBase;
	cout << "Enter a base between 2 and 36 to convert to: ";
	cin >> iBase;
	//If the source base is not 10, convert it to 10 first
	if(iSrcBase!=10)
		iInput = BaseToDec(number,iSrcBase);
	else
		iInput = atoi(number);

	//If source base is not 10, and the destination base is, it is not nessecery to run DecToBase as the number
	//Has already been found in base 10
	if(iSrcBase!=10&&iBase==10)
	{
		cout << number << " in base " << iSrcBase << " = " << iInput << " in base " << iBase << endl << endl;
	}
	else
	{
		if(DecToBase(iBase,iInput,number))
			cout << iInput << " in base " << iSrcBase << " = " << number << " in base " << iBase << endl << endl;
		else
			cout << "Error: Base was out of bounds... (must be between 2 and 36)\n\n";
	}
	return 0;
}

int DecToBase(int base, long iDec, char* szString)
{
	//Check base is between 2 and 36
	if(base<2||base>MAX_BASE)
		return 0; //Failed
	//If input is 0, output is 0
	if(iDec==0){
		strcpy(szString,"0");
		return 1;
	}
	
	int count = 0;
	char chResult[256] = "";
	char* pChResult = chResult;
	while(iDec > 0 && count++<256)
	{
		*pChResult = symbols[iDec % base];
		pChResult++;
		iDec = iDec/base;	//iDec = itself divided by base
	}
	strcpy(chResult,_strrev(chResult));	
	strcpy(szString,chResult);

	return 1;
}

int BaseToDec(char* number, int base)
{
	if(base<2||base>MAX_BASE)
		return 0; //Failed

	int NumLength = strlen(number);
	int PlaceValue, total = 0;
	//Work out the place value of the first digit (base^length-1)
	PlaceValue = (int)pow(base,NumLength-1);
	
	//For each digit, multiply by its place value and add to total
	for(int i=0;i<NumLength;i++)
	{
		total += GetIndex(symbols,*number)*PlaceValue;
		number++;
		PlaceValue /= base; //Next digit's place value (previous/base)
	}
	return total;
}

//Finds the index of a particular character (if it exists) in an array. Returns last character on failure
//Used by BaseToDec to find face values
int GetIndex(char * pString, char search)
{
	int index = 0;
	while(*pString != (char)0) //Loop will finish at null character if no match is found
	{
		if(*pString==search)
			break;
		pString++;
		index++;
	}
	return index;
}

Copyright © 2003-2007 Matt Squire. All rights reserved. No content may be duplicated without express written permission.
Hand coded by a thousand monkeys under the direction of Matt Squire
contact: mattsquire at insidereality dot net | Legal stuff

Everyone go to Inside Reality for free beer (note: free beer may be metaphorical)