Java Byte Array Encode encode(byte[] buff)

Here you can find the source of encode(byte[] buff)

Description

encode

License

Apache License

Declaration

public synchronized static String encode(byte[] buff) 

Method Source Code


//package com.java2s;
/*/*  ww  w.ja v  a 2 s  . c o m*/
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import java.io.UnsupportedEncodingException;

public class Main {
    private static final String BASE64_CODE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz"
            + "0123456789" + "+/";

    public synchronized static String encode(byte[] buff) {
        if (null == buff)
            return null;

        StringBuilder strBuilder = new StringBuilder("");
        int paddingCount = (3 - (buff.length % 3)) % 3;
        byte[] stringArray = zeroPad(buff.length + paddingCount, buff);
        for (int i = 0; i < stringArray.length; i += 3) {
            int j = ((stringArray[i] & 0xff) << 16) + ((stringArray[i + 1] & 0xff) << 8)
                    + (stringArray[i + 2] & 0xff);
            strBuilder.append(BASE64_CODE.charAt((j >> 18) & 0x3f));
            strBuilder.append(BASE64_CODE.charAt((j >> 12) & 0x3f));
            strBuilder.append(BASE64_CODE.charAt((j >> 6) & 0x3f));
            strBuilder.append(BASE64_CODE.charAt(j & 0x3f));
        }
        int intPos = strBuilder.length();
        for (int i = paddingCount; i > 0; i--) {
            strBuilder.setCharAt(intPos - i, '=');
        }

        return strBuilder.toString();
    }

    public synchronized static String encode(String string, String encoding) throws UnsupportedEncodingException {
        if (null == string || null == encoding)
            return null;
        byte[] stringArray = string.getBytes(encoding);
        return encode(stringArray);
    }

    private static byte[] zeroPad(int length, byte[] bytes) {
        byte[] padded = new byte[length];
        System.arraycopy(bytes, 0, padded, 0, bytes.length);
        return padded;
    }
}

Related

  1. encode(byte[] b)
  2. encode(byte[] buf)
  3. encode(byte[] buffer, int offset, int len, Writer out)
  4. encode(byte[] bytes)
  5. encode(byte[] bytes, boolean withNewLines)
  6. encode(byte[] data)