Na wielu serwisach zamiast numeru ID dla zasobu możemy się spotkać z ciągiem znaków. Nazwijmy to skróconą reprezentacją tekstową.
Przykładami jest youtube, megavideo jak jeszcze istniało czy też wszelkie serwisy do skracania linków (tnij.org).
Generalnie można użyć do tego przerobionego base64 ze zmienionymi 2 znakami, lecz base64 koduje tekst nie liczby, przez co daje dłuższy ciąg wynikowy.

Idea jest prosta. Gdy dla przykładu zamieniamy liczby dziesiętne na szesnastkowe, liczby szesnastkowe składają się ze znaków 0-9a-f, co daje nam 16 możliwości na 1 znak.
My wykorzystamy znaki 0-9a-zA-Z co daje nam 62 możliwości na 1 znak.

Algorytmy na przeliczanie nie różnią się niczym od zamiany systemu binarnego na dziesiętny, tylko podstawa jest inna.
A oto i kod:

<?php
 
/**
 * Convert numeric ID representation to shorter string representation
 * f.e. 15100900 = 11mqU
 * 
 * @author programista.it
 * @package IdNumberConverter
 */
 
class IdNumberConverter {
  private $map;
  private $base;
 
  function __construct() {
    // 0-9, a-z, A-Z
    foreach (array(48 => 57, 97 => 122, 65 => 90) as $min => $max) {
      for ($i = $min; $i <= $max; $i++) {
        $this -> map[] = chr($i);
      }
    }
    $this -> base = count($this -> map);
  }
 
  /**
   * Converts numeric ID to string ID
   * 
   * @param integer $number The number
   * 
   * @return string Shorter string representation
   */
  function convertToId($number) {
    $result = '';
    while ($number > 0) {
      $result = $this -> map[$number % $this -> base] . $result;
      $number = floor($number / $this -> base);
    }
    return $result;
  }
 
  /**
   * Converts string ID to numeric ID
   * 
   * @param string $id The string representation
   * 
   * @return integer The numeric representation
   */
  function convertToNumber($id) {
    $p = 1;
    $result = 0;
    for ($i = strlen($id) - 1; $i >= 0; $i--) {
      $result += $p * array_search($id[$i], $this -> map);
      $p *= $this -> base;
    }
    return $result;
  }
}

a oto jak tego używać

$c = new IdNumberConverter();
echo base64_encode(1896762155) . "\n"; // MTg5Njc2MjE1NQ==
echo $c -> convertToId(1896762155) . "\n"; // 24mCtZ
echo $c -> convertToNumber('24mCtZ') . "\n"; // 1896762155

Nie znaleziono żadnych powiązanych wpisów.