Java Base Convert fromBase58(String input)

Here you can find the source of fromBase58(String input)

Description

from Base

License

Open Source License

Declaration

public static byte[] fromBase58(String input) throws Exception 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    private static final int[] indexes58 = new int[128];

    public static byte[] fromBase58(String input) throws Exception {
        if (input.length() == 0) {
            return new byte[0];
        }/*from   w  w  w .j a  v a  2s.  c  om*/
        byte[] input58 = new byte[input.length()];
        // Transform the String to a base58 byte sequence
        for (int i = 0; i < input.length(); ++i) {
            char c = input.charAt(i);

            int digit58 = -1;
            if (c >= 0 && c < 128) {
                digit58 = indexes58[c];
            }
            if (digit58 < 0) {
                throw new Exception("Illegal character " + c + " at " + i);
            }

            input58[i] = (byte) digit58;
        }
        // Count leading zeroes
        int zeroCount = 0;
        while (zeroCount < input58.length && input58[zeroCount] == 0) {
            ++zeroCount;
        }
        // The encoding
        byte[] temp = new byte[input.length()];
        int j = temp.length;

        int startAt = zeroCount;
        while (startAt < input58.length) {
            byte mod = divmod256(input58, startAt);
            if (input58[startAt] == 0) {
                ++startAt;
            }

            temp[--j] = mod;
        }
        // Do no add extra leading zeroes, move j to first non null byte.
        while (j < temp.length && temp[j] == 0) {
            ++j;
        }

        return copyOfRange(temp, j - zeroCount, temp.length);
    }

    private static byte divmod256(byte[] number58, int startAt) {
        int remainder = 0;
        for (int i = startAt; i < number58.length; i++) {
            int digit58 = (int) number58[i] & 0xFF;
            int temp = remainder * 58 + digit58;
            number58[i] = (byte) (temp / 256);
            remainder = temp % 256;
        }
        return (byte) remainder;
    }

    private static byte[] copyOfRange(byte[] source, int from, int to) {
        byte[] range = new byte[to - from];
        System.arraycopy(source, from, range, 0, range.length);
        return range;
    }
}

Related

  1. fromBase16toByteArray(String bytes)
  2. fromBase16toIntArray(String bytes)
  3. fromBase26(String number)
  4. fromBase36(String base36)
  5. fromBase36(String base36Number)
  6. fromBase62(String base62Number)