November 2, 2009

How to convert an int to a character array when you don’t have access to the C++ Standard Library?

Filed under: Development — J. Abram barneck @ 3:44 am

Ok, so I have a great way to convert and int (or any other type) to a string using the stringstream from the standard library. This is listed here:
How to convert an int to a string in C++? (Also doubles, floats, etc…)

However, what do you do if you don’t have access to the C++ Standard Library? There is not stringstream or string so the solution in the above linked-to post won’t work.

So I have created a simple class Int.h that can do this conversion without the C++ Standard Library. Notice it is Int.h with a capital “I”.

It handles both positive and negative numbers.


#pragma once

class Int
	// Constructor
	Int(int inInt);

	// Desctructor

	// Public functions
	void intToCharArray(char inChar[]);
	char * intToCharArrayPointer();

	// Members
	int mInteger;

	// Functions
	char digitToChar(int inInt);


#include "Int.h"

Int::Int(int inInt)
	mInteger = inInt;


char Int::digitToChar(int inInt)
	char digit[11] = {'0','1','2','3','4','5','6','7','8','9'};
	//digit[0] = '';
	for (short i = 0; i < 10; i++)
		if (inInt == i)
			return digit[i];
	return '';

void Int::intToCharArray(char inChar[])
	char tmpVal[11]; 
	int tmpInt = mInteger;
	bool isNegative = false;

	if (mInteger < 0)
		tmpInt *= -1;
		isNegative = true;

	short i = 0;
	while (tmpInt > 0)
		int rightDigit = tmpInt % 10;
		tmpVal[i] = digitToChar(rightDigit);
		tmpInt = tmpInt/10;
	tmpVal[i--] = '';
	// tmpVal should now be the number in reverse.

	short j = 0;
	if (isNegative)
		inChar[j++] = '-';
	while (i > -1)
		inChar[j++] = tmpVal[i--];
	inChar[j] = '';
	// inChar should now be the number in correct order.

char * Int::intToCharArrayPointer()
	// Integers hold as many as 10 character, plus 1 for the null char.
	char * retVal = new char[11];
	return retVal;

Here is a quick example of how to use it. Load this up in your favorite IDE/debugger.


#include "Int.h"

int main()
	Int int1 = 1027;
	Int int2 = -2387809;

	char * charPtr = int1.intToCharArrayPointer();
	char charBuff[11];

I haven’t seen it fail to convert any integers, positive or negative yet. Let me know if you see anything I could improve on.


Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: