01: //==============================================================================
02: //===
03: //=== Codec (adapted class from druid project http://druid.sf.net)
04: //===
05: //=== Copyright (C) by Andrea Carboni.
06: //=== This file may be distributed under the terms of the GPL license.
07: //==============================================================================
08:
09: package org.fao.gast.lib.druid;
10:
11: import org.dlib.tools.Util;
12:
13: //==============================================================================
14:
15: public class Codec {
16: public static String encodeString(String s) {
17: StringBuffer sb = new StringBuffer();
18:
19: for (int i = 0; i < s.length(); i++) {
20: char c = s.charAt(i);
21:
22: if (c >= 32 && c < 126)
23: sb.append(c);
24: else
25: sb.append("~" + Util.convertToHex(c, 4));
26: }
27:
28: return sb.toString();
29: }
30:
31: //---------------------------------------------------------------------------
32:
33: public static String decodeString(String s) {
34: StringBuffer sb = new StringBuffer();
35:
36: for (int i = 0; i < s.length(); i++) {
37: char c = s.charAt(i);
38:
39: if (c == '~') {
40: String hv = s.substring(i + 1, i + 5);
41: i += 4;
42:
43: c = (char) Util.convertFromHex(hv);
44: }
45:
46: sb.append(c);
47: }
48:
49: return sb.toString();
50: }
51:
52: //---------------------------------------------------------------------------
53:
54: public static String encodeBytes(byte[] data) {
55: StringBuffer sb = new StringBuffer();
56:
57: for (int i = 0; i < data.length; i++)
58: sb.append(Util.convertToHex(data[i], 2));
59:
60: return sb.toString();
61: }
62:
63: //---------------------------------------------------------------------------
64:
65: public static byte[] decodeBytes(String data) {
66: byte[] array = new byte[data.length() / 2];
67:
68: for (int i = 0; i < data.length() / 2; i++) {
69: String hv = data.substring(i * 2, i * 2 + 2);
70: array[i] = (byte) Util.convertFromHex(hv);
71: }
72:
73: return array;
74: }
75: }
76:
77: //==============================================================================
|