Skip to content

Instantly share code, notes, and snippets.

@edbartley
Created October 4, 2012 15:21
Show Gist options
  • Save edbartley/3834341 to your computer and use it in GitHub Desktop.
Save edbartley/3834341 to your computer and use it in GitHub Desktop.
C++ functions to convert an int to a C string and back again
char* intToStr(int value)
{
int divisor = 1;
int bufferLength = 1;
int isNegative = 0;
int bufferIndex = 0;
// Handle the negative value case by remebering that the number is negative
// and then setting it positive
if(value < 0)
{
isNegative = 1;
value *= -1;
bufferIndex++; // move 1 place in the buffer so we don't overwrite the '-'
}
// Determine the length of the integer so we can allocate a string buffer
while(value / divisor >= 10)
{
divisor *= 10;
bufferLength++;
}
// Create the resulting char buffer that we'll return.
// bufferLength + 1 because we need a terminating NULL character.
// + isNegative because we need space for the negative sign, if necessary.
char *result = new char[bufferLength + 1 + isNegative];
// Set the first character to NULL or a negative sign
result[0] = isNegative == false ? 0 : '-';
while(bufferLength > 0)
{
// ASCII table has the number characters in sequence from 0-9 so use the
// ASCII value of '0' as the base
result[bufferIndex] = '0' + value / divisor;
// This removes the most significant digit converting 1337 to 337 because
// 1337 % 1000 = 337
value = value % divisor;
// Adjust the divisor to next lowest position
divisor = divisor / 10;
bufferIndex++;
bufferLength--;
}
// NULL terminate the string
result[bufferIndex] = 0;
return result;
}
// Assumes the incoming char* is null terminated, the function does not modify
// str.
// Assumes a positive number is *not* prepended with a '+' character.
// Assumes a negative number *is* prepended with a '-' character.
// Assumes that all characters in the str are from '0' to '9' or '-'. Will
// return wonky numbers otherwise.
// Returns 0 if str == NULL.
int strToInt(const char* str)
{
if(str == NULL)
{
return 0;
}
int stringLength = 0;
int returnValue = 0;
int multiplier = 1;
int stopPoint = str[0] == '-' ? 1 : 0;
// Find the length of the incoming string
while(str[stringLength] != 0)
{
stringLength++;
}
// Back up one so that stringLength indexes the least significant character
stringLength--;
while(stringLength >= stopPoint)
{
// Use the ASCII value for '0' as the base - the ASCII value of the char
// at str position stringLength
returnValue += (str[stringLength] - '0') * multiplier;
multiplier *= 10;
stringLength--;
}
// Handle the case of a negative number
if(stopPoint == 1)
{
returnValue *= -1;
}
return returnValue;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment