Encodes binary data in base32. - Java java.lang

Java examples for java.lang:byte Array Encode Decode

Description

Encodes binary data in base32.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] bytes = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(encode(bytes));
    }/*from w ww .ja v a 2s  .c  o m*/

    /**
     * Encodes binary data in base32.
     * 
     * @param bytes
     *            binary data
     * @return base32 encoding
     */
    static public String encode(final byte[] bytes) {
        final StringBuilder r = new StringBuilder(bytes.length * 8 / 5 + 1);
        int buffer = 0;
        int bufferSize = 0;
        for (final byte b : bytes) {
            buffer <<= 8;
            buffer |= b & 0xFF;
            bufferSize += 8;
            while (bufferSize >= 5) {
                bufferSize -= 5;
                r.append(at((buffer >>> bufferSize) & 0x1F));
            }
        }
        if (0 != bufferSize) {
            buffer <<= 5 - bufferSize;
            r.append(at(buffer & 0x1F));
        }
        return r.toString();
    }

    static private char at(final int v) {
        return (char) (v < 26 ? v + 'a' : v - 26 + '2');
    }
}

Related Tutorials