long value to Base 62 - Java java.lang

Java examples for java.lang:long

Description

long value to Base 62

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        long number = 2;
        System.out.println(toBase62(number));
    }/*from w  w  w  . ja  v  a 2  s .  com*/

    private static String alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public static String toBase62(long number) {
        return toBase(number, 62);
    }

    private static String toBase(long number, int base) {
        if (number < base) {
            return Character.toString(alphabet.charAt((int) number));
        }

        long value = number;
        StringBuffer sb = new StringBuffer();

        while (value != 0) {
            int remind = (int) (value % base);
            value = (value - remind) / base;
            sb.append(alphabet.charAt(remind));
        }

        return sb.toString();
    }
}

Related Tutorials