int to string conversion

Conversion using a dictionary

This technique is usually faster for small numbers. For example, it is used in Golang for numbers that are less than 100.

The idea is to use a dictionary to transform an integer into its string representation. The dictionary looks like this:

Interger String
0 "0"
1 "1"
...

For numbers that are less than 10 it is pretty straightforward, it is a basic lookup in the table.
For bigger numbers we need to divide it by its base until it goes in the first case.

Here is my own implementation written in JavaScript:

JavaScript
        
// Char set
const cs = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];

function intToString(n, base = 10) {
  let res = "";

  // 0 is a special case
  if (n == 0) {
    return "0";
  }

  while(n > 0) {
    res = cs[n % base] + res;
    n = parseInt(n / base);
  }

  return res;
}
        
      

Conversion using bit shifting

This section will be detailed soon.

Contact me

Sven Sauleau

Say hello: sven.sauleau@xtuc.fr.

Ping me on Twitter: @svensauleau.

© XTUC SAS
N° SIRET : 821 797 891 00016, RCS Strasbourg TI 821 797 891