KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > ui > wizards > datatransfer > Base64Encoder


1 /*******************************************************************************
2  * Copyright (c) 2000, 2003 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Common Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/cpl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.ui.wizards.datatransfer;
12
13
14 /**
15  * This utility class converts a passed byte array into a Base 64 encoded
16  * String according to the specification in RFC1521 section 5.2
17  */

18 /*package*/ class Base64Encoder {
19     private static final String JavaDoc mappings = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";//$NON-NLS-1$
20
private static final String JavaDoc filler = "=";//$NON-NLS-1$
21
/**
22  * Answer a string representing the Base 64 encoded form of the passed
23  * byte array
24  *
25  * @return java.lang.String
26  * @param contents byte[]
27  */

28 public static String JavaDoc encode(byte[] contents) {
29     StringBuffer JavaDoc result = new StringBuffer JavaDoc();
30
31     for (int i = 0; i < contents.length; i = i + 3) {
32         if (result.length() == 76)
33             result.append("\n\r");//$NON-NLS-1$
34

35         // output character 1
36
result.append(mappings.charAt((contents[i] & 0xFC) >> 2));
37
38         // output character 2
39
int c2 = (contents[i] & 0x03) << 4;
40         if (i + 1 >= contents.length) {
41             result.append(mappings.charAt(c2));
42             result.append(filler);
43             result.append(filler);
44             return result.toString();
45         }
46         
47         c2 |= ((contents[i + 1] & 0xF0) >> 4);
48         result.append(mappings.charAt(c2));
49
50         // output character 3
51
int c3 = (contents[i + 1] & 0x0F) << 2;
52         if (i + 2 >= contents.length) {
53             result.append(mappings.charAt(c3));
54             result.append(filler);
55             return result.toString();
56         }
57         
58         c3 |= ((contents[i + 2] & 0xC0) >> 6);
59         result.append(mappings.charAt(c3));
60
61         // output character 4
62
result.append(mappings.charAt(contents[i + 2] & 0x3F));
63     }
64         
65     return result.toString();
66 }
67 }
68
Popular Tags