Base conversion

From CodeCodex

Implementations[edit]

C++[edit]

/* A simple implementation of itoa (integer to string conversion)
 and atoi (string to interger conversion). No error checking, and only works
 with upper-case letters (use "DEADBEEF", not "deadbeef") */

#include <string>
#include <algorithm>
#include <cassert>

std::string digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

std::string my_itoa(int src, int radix) {
    assert(radix >= 2 && radix <= 36);
    std::string str;
    for ( ; src > 0; src /= radix) {
        str += digits[src % radix];
    }
    std::reverse(str.begin(), str.end()); // reverse string
    return str;
}

int my_atoi(std::string src, int radix)
{
    assert(radix >= 2 && radix <= 36);
    int dest = 0;

    //it seems that use "!=" is more security
    for (std::string::iterator i = src.begin(); /*i < src.end()*/i != src.end(); ++i) {
        dest = dest * radix + digits.find(*i);
    }

    return dest;
}

Erlang[edit]

Num = erlang:list_to_integer("ffff", 16).    % 65535

Str = erlang:integer_to_list(63, 2).         % "111111"

Java[edit]

Java's library already includes functions for doing this:

int num = Integer.parseInt(str, radix);
long num2 = Long.parseLong(str, radix);

String str = Integer.toString(num, radix);
String str = Long.toString(num2, radix);

JavaScript[edit]

var num = parseInt(str, radix);

var str = num.toString(radix);

Python[edit]

# Parsing string with base into a number is easy
num = int(str, radix)

# We have to write our own function for outputting to string with arbitrary base
def itoa(num, radix):
  result = ""
  while num > 0:
    result = "0123456789abcdefghijklmnopqrstuvwxyz"[num % radix] + result
    num /= radix
  return result

Ruby[edit]

Returns a string containing the representation of fix radix base (between 2 and 36).

str = 15.to_s(2)        #=> "1111"
str = 35.to_s(36)       #=> "z"

num = "ffff".to_i(16)   #=> 65535