source: josm/trunk/src/org/openstreetmap/josm/tools/Base64.java@ 4077

Last change on this file since 4077 was 3840, checked in by stoecker, 13 years ago

switch to internal base64 again

  • Property svn:eol-style set to native
File size: 2.3 KB
Line 
1// License: GPL. Copyright 2007 by Immanuel Scholz and others
2package org.openstreetmap.josm.tools;
3
4import java.nio.ByteBuffer;
5
6public class Base64 {
7
8 private static String encDefault = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
9 private static String encUrlSafe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
10
11 public static String encode(String s) {
12 return encode(s, false);
13 }
14
15 public static String encode(String s, boolean urlsafe) {
16 StringBuilder out = new StringBuilder();
17 String enc = urlsafe ? encUrlSafe : encDefault;
18 for (int i = 0; i < (s.length()+2)/3; ++i) {
19 int l = Math.min(3, s.length()-i*3);
20 String buf = s.substring(i*3, i*3+l);
21 out.append(enc.charAt(buf.charAt(0)>>2));
22 out.append(enc.charAt(
23 (buf.charAt(0) & 0x03) << 4 |
24 (l==1?
25 0:
26 (buf.charAt(1) & 0xf0) >> 4)));
27 out.append(l>1?enc.charAt((buf.charAt(1) & 0x0f) << 2 | (l==2?0:(buf.charAt(2) & 0xc0) >> 6)):'=');
28 out.append(l>2?enc.charAt(buf.charAt(2) & 0x3f):'=');
29 }
30 return out.toString();
31 }
32
33 public static String encode(ByteBuffer s) {
34 return encode(s, false);
35 }
36
37 public static String encode(ByteBuffer s, boolean urlsafe) {
38 StringBuilder out = new StringBuilder();
39 String enc = urlsafe ? encUrlSafe : encDefault;
40 // Read 3 bytes at a time.
41 for (int i = 0; i < (s.limit()+2)/3; ++i) {
42 int l = Math.min(3, s.limit()-i*3);
43 int byte0 = s.get() & 0xff;
44 int byte1 = l>1? s.get() & 0xff : 0;
45 int byte2 = l>2? s.get() & 0xff : 0;
46
47 out.append(enc.charAt(byte0>>2));
48 out.append(enc.charAt(
49 (byte0 & 0x03) << 4 |
50 (l==1?
51 0:
52 (byte1 & 0xf0) >> 4)));
53 out.append(l>1?enc.charAt((byte1 & 0x0f) << 2 | (l==2?0:(byte2 & 0xc0) >> 6)):'=');
54 out.append(l>2?enc.charAt(byte2 & 0x3f):'=');
55 }
56 return out.toString();
57 }
58}
Note: See TracBrowser for help on using the repository browser.