# How to convert a number into any base

Most of the URL shortner websites work on the logic of converting random numbers to higher base numbers so that we can accommodate more characters at each position. This is the logic of converting a decimal base number into any base number

import java.util.concurrent.ThreadLocalRandom; public class BaseConversion { private static char[] code = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" .toCharArray(); static int base = code.length; public static void main(String[] args) { long number = ThreadLocalRandom.current().nextLong(56800235584l); System.out.println("Random number is " + number); long div = number; int mod = 0; String shortURL = ""; while (div > 0) { mod = (int) (div % base); div = (int) (div / base); shortURL += code[mod]; } System.out.println(shortURL); } } |