KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > proxy > Base64Encoder


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.proxy;
21
22 /**
23  * Bas64 encode utility class.
24  *
25  * @author Maros Sandor
26  */

27 class Base64Encoder {
28
29     private static final char [] characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
30
31     private Base64Encoder() {
32     }
33
34     public static String JavaDoc encode(byte [] data) {
35         int length = data.length;
36         StringBuffer JavaDoc sb = new StringBuffer JavaDoc(data.length * 3 / 2);
37
38         int end = length - 3;
39         int i = 0;
40
41         while (i <= end) {
42             int d = ((((int) data[i]) & 0xFF) << 16) | ((((int) data[i + 1]) & 0xFF) << 8) | (((int) data[i + 2]) & 0xFF);
43             sb.append(characters[(d >> 18) & 0x3F]);
44             sb.append(characters[(d >> 12) & 0x3F]);
45             sb.append(characters[(d >> 6) & 0x3F]);
46             sb.append(characters[d & 0x3F]);
47             i += 3;
48         }
49
50         if (i == length - 2) {
51             int d = ((((int) data[i]) & 0xFF) << 16) | ((((int) data[i + 1]) & 0xFF) << 8);
52             sb.append(characters[(d >> 18) & 0x3F]);
53             sb.append(characters[(d >> 12) & 0x3F]);
54             sb.append(characters[(d >> 6) & 0x3F]);
55             sb.append("=");
56         } else if (i == length - 1) {
57             int d = (((int) data[i]) & 0xFF) << 16;
58             sb.append(characters[(d >> 18) & 0x3F]);
59             sb.append(characters[(d >> 12) & 0x3F]);
60             sb.append("==");
61         }
62         return sb.toString();
63     }
64 }
65
Popular Tags