Decodes base32 data to binary. - Java java.lang

Java examples for java.lang:byte Array Encode Decode

Description

Decodes base32 data to binary.

Demo Code


//package com.java2s;
import java.io.UnsupportedEncodingException;

public class Main {
    public static void main(String[] argv) throws Exception {
        String chars = "java2s.com";
        System.out.println(java.util.Arrays.toString(decode(chars)));
    }// w w w .  j a va 2  s  .c om

    /**
     * Decodes base32 data to binary.
     * 
     * @param chars
     *            base32 data
     * @return decoded binary data
     * @throws InvalidBase32
     *             decoding error
     */
    static public byte[] decode(final String chars)
            throws UnsupportedEncodingException {
        final int end = chars.length();
        final byte[] r = new byte[end * 5 / 8];
        int buffer = 0;
        int bufferSize = 0;
        int j = 0;
        for (int i = 0; i != end; ++i) {
            final char c = chars.charAt(i);
            buffer <<= 5;
            buffer |= locate(c);
            bufferSize += 5;
            if (bufferSize >= 8) {
                bufferSize -= 8;
                r[j++] = (byte) (buffer >>> bufferSize);
            }
        }
        if (0 != (buffer & ((1 << bufferSize) - 1))) {
            invalid();
        }
        return r;
    }

    static private int locate(final char c)
            throws UnsupportedEncodingException {
        return 'a' <= c && 'z' >= c ? c - 'a'
                : '2' <= c && '7' >= c ? 26 + (c - '2') : 'A' <= c
                        && 'Z' >= c ? c - 'A' : invalid();
    }

    static private int invalid() throws UnsupportedEncodingException {
        throw new UnsupportedEncodingException();
    }
}

Related Tutorials