Java Base64 Encode toBase64(byte[] buf, int start, int length)

Here you can find the source of toBase64(byte[] buf, int start, int length)

Description

to Base

License

Open Source License

Declaration

public static byte[] toBase64(byte[] buf, int start, int length) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2007 JCraft, Inc./*from   ww  w  . j a  va 2s.com*/
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     JCraft, Inc. - initial API and implementation
 *******************************************************************************/

public class Main {
    private static final byte[] b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
            .getBytes();

    public static byte[] toBase64(byte[] buf, int start, int length) {

        byte[] tmp = new byte[length * 2];
        int i, j, k;

        int foo = (length / 3) * 3 + start;
        i = 0;
        for (j = start; j < foo; j += 3) {
            k = (buf[j] >>> 2) & 0x3f;
            tmp[i++] = b64[k];
            k = (buf[j] & 0x03) << 4 | (buf[j + 1] >>> 4) & 0x0f;
            tmp[i++] = b64[k];
            k = (buf[j + 1] & 0x0f) << 2 | (buf[j + 2] >>> 6) & 0x03;
            tmp[i++] = b64[k];
            k = buf[j + 2] & 0x3f;
            tmp[i++] = b64[k];
        }

        foo = (start + length) - foo;
        if (foo == 1) {
            k = (buf[j] >>> 2) & 0x3f;
            tmp[i++] = b64[k];
            k = ((buf[j] & 0x03) << 4) & 0x3f;
            tmp[i++] = b64[k];
            tmp[i++] = (byte) '=';
            tmp[i++] = (byte) '=';
        } else if (foo == 2) {
            k = (buf[j] >>> 2) & 0x3f;
            tmp[i++] = b64[k];
            k = (buf[j] & 0x03) << 4 | (buf[j + 1] >>> 4) & 0x0f;
            tmp[i++] = b64[k];
            k = ((buf[j + 1] & 0x0f) << 2) & 0x3f;
            tmp[i++] = b64[k];
            tmp[i++] = (byte) '=';
        }
        byte[] bar = new byte[i];
        System.arraycopy(tmp, 0, bar, 0, i);
        return bar;
    }
}

Related

  1. encodeBase64(InputStream is, OutputStream os)
  2. encodeBase64(String data)
  3. encodeBase64(String data)
  4. toBase64(byte[] array)
  5. toBase64(byte[] aValue)
  6. toBase64(byte[] data)
  7. toBase64(byte[] data)
  8. toBase64(final byte[] bytes)
  9. toBase64(final byte[] value)