---
title: "JAVA : Comment faire un hash court d'un nombre ?"
canonical: "https://blog.kaptus.net/space/BKAP/blog/167051265/JAVA%20%3A%20Comment%20faire%20un%20hash%20court%20d'un%20nombre%20%3F"
format: markdown
---
## Problème

Comment créer un lien court à partir d'un nombre (identifiant par exemple) ?

## Solution

L'idée trouvée sur le [net](https://www.geeksforgeeks.org/how-to-design-a-tiny-url-or-url-shortener/), est de créer une chaine de caractères (de 62 éléments) et d'itérer sur les éléments en fonction du nombre à convertir (**l'équivalent d'un nombre en ****[base 62](https://en.wikipedia.org/wiki/Base62)**), donc pas de collision car l'association est [bijective](https://fr.wikipedia.org/wiki/Bijection). L'avantage est que l'opération est réversible assez simplement. 

Le code java ci-dessous :

```java
package com.kaptus.testing;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class CreateShortUrl
{
    public static void main(String[] args) throws IOException
    {
        int n = 256781;
        String shorturl = idToShortURL(n);
        System.out.println("Generated short url is " + shorturl);
        System.out.println("Id from url is " + shortURLtoID(shorturl));
    }

    // Function to generate a short url from integer ID
    static String idToShortURL(int n)
    {
        // Map to store 62 possible characters
        char map[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();

        StringBuffer shorturl = new StringBuffer();

        // Convert given integer id to a base 62 number
        while (n > 0)
        {
            // use above map to store actual character
            // in short url
            shorturl.append(map[n % 62]);
            n = n / 62;
        }

        // Reverse shortURL to complete base conversion
        return shorturl.reverse().toString();
    }

    // Function to get integer ID back from a short url
    static int shortURLtoID(String shortURL)
    {
        int id = 0; // initialize result
        // A simple base conversion logic
        for (int i = 0; i < shortURL.length(); i++)
        {
            if ('a' <= shortURL.charAt(i) &&
                    shortURL.charAt(i) <= 'z')
                id = id * 62 + shortURL.charAt(i) - 'a';
            if ('A' <= shortURL.charAt(i) &&
                    shortURL.charAt(i) <= 'Z')
                id = id * 62 + shortURL.charAt(i) - 'A' + 26;
            if ('0' <= shortURL.charAt(i) &&
                    shortURL.charAt(i) <= '9')
                id = id * 62 + shortURL.charAt(i) - '0' + 52;
        }
        return id;
    }
}

```

  


## Articles connexes



> Macro (contentbylabel)