Base58 Converter


package org.wiztools.base58;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 *
 * @author subwiz
 */
public class Base58 {

    private final static char[] BASE58 = "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ".toCharArray();

    static String asBase58(final long value) {
        long val = value;
        if(val < Long.valueOf(BASE58.length)) {
            return String.valueOf(BASE58[(int)val]);
        }

        final List<Long> reminderList = new ArrayList<Long>();
        while(true) {
            final long reminder = val % BASE58.length;
            reminderList.add(reminder);

            val = val / BASE58.length;

            if(val < BASE58.length) {
                // for Flickr Url shortening, do not subtract by 1L:
                reminderList.add(val-1L);
                break;
            }
        }

        // Reverse the list:
        Collections.reverse(reminderList);

        final StringBuilder sb = new StringBuilder();
        for(long l: reminderList) {
            sb.append(BASE58[(int)l]);
        }
        return sb.toString();
    }
}
Posted on May 30, 2010 02:38 PM by Subhash Chandran
java base58 algorithm