CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com

# Thread: Integer to string and vice-verca for any base

1. ## Integer to string and vice-verca for any base

Q: How do I convert integers to string and vice-verca for any base from binary to hex?

A: It is seen many times in this forum questions like "I have a hex number which I wanted to convert into decimal" and stuffs similar to this. One should understand that the numbers are represented in only one way but can be displayed in binary, octal, decimal or hex.

Here are two functions, first to convert an integer to its string representation and second to convert a string back to the integer. It is very simple code and I have made it general so that it can be used not only for binary, octal, decimal and hex bases, but any base between 2 and 16. Here are the functions:

Code:
```[I]#include <string>

typedef unsigned char base;

std::string itos(int i, base b = 10)
{
b = b > 1 && b <= 16 ? b : 10;
std::string s = "";
return (s += i < b ? "" : itos(i / b, b)) + mask[i % b];
}

int stoi(std::string s, base b = 10)
{
b = b > 1 && b <= 16 ? b : 10;
for (int i = 0, no = 0, pos; i < s.length(); i++)
no = (pos = mask.find(s)) >= 0 ? b * no + pos : no;
return no;
}```
I have used std::string for one end of the conversion, but with minor modification, conversion to character array or CArray also can be done.

First line of both the functions checks whether the base is within the valid range from 2 to 16 and sets it to the default base of 10 (decimal) if it is not within the valid range. In the first function, the number is stripped to its modulo with respect to the base and added to string representation of the divident, which is recursively evaluated. In the second function, number is reconstructed by repeatedly multiplying by base and adding the number corresponding to the character in the string.
Last edited by cilu; June 1st, 2007 at 02:31 AM.  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
• 