Android Base64 Byte Array Encode encodeLast2Bytes(byte bytes[])

Here you can find the source of encodeLast2Bytes(byte bytes[])

Description

encode Last Bytes

Declaration

private static String encodeLast2Bytes(byte bytes[]) 

Method Source Code

//package com.java2s;

public class Main {
    private static String encodeLast2Bytes(byte bytes[]) {
        byte firstByte = bytes[bytes.length - 2];
        byte secondByte = bytes[bytes.length - 1];

        StringBuffer resultBuffer = new StringBuffer();

        byte bufferByte = 0;

        bufferByte = (byte) (firstByte >> 2);
        resultBuffer.append(encodeBase64Byte(bufferByte));

        bufferByte = (byte) (((firstByte & 0x03) << 4) | (secondByte >> 4));
        resultBuffer.append(encodeBase64Byte(bufferByte));

        bufferByte = (byte) ((secondByte & 0x0F) << 2);
        resultBuffer.append(encodeBase64Byte(bufferByte));

        resultBuffer.append('=');

        return resultBuffer.toString();
    }//  w  w  w.  ja v a2 s.  co  m

    private static char encodeBase64Byte(byte base64Byte) {
        if ((base64Byte >= 0) && (base64Byte <= 25)) {
            return (char) (base64Byte + 65);
        } else if ((base64Byte >= 26) && (base64Byte <= 51)) {
            return (char) (base64Byte - 26 + 97);
        } else if ((base64Byte >= 52) && (base64Byte <= 61)) {
            return (char) (base64Byte - 52 + 48);
        } else if (base64Byte == 62) {
            return '+';
        } else if (base64Byte == 63) {
            return '/';
        } else {
            return '0';
        }
    }
}

Related

  1. encode(byte[] data)
  2. encodeWebSafe(byte[] source, boolean doPadding)
  3. encode(byte[] bytes)
  4. encode(byte[] data)
  5. encodeBase64Byte(byte base64Byte)
  6. encodeLast1Byte(byte bytes[])
  7. encode(byte[] data)
  8. encode(byte[] data)
  9. encode(byte raw[])