01: /**
02: * Sequoia: Database clustering technology.
03: * Copyright (C) 2002-2004 French National Institute For Research In Computer
04: * Science And Control (INRIA).
05: * Contact: sequoia@continuent.org
06: *
07: * Licensed under the Apache License, Version 2.0 (the "License");
08: * you may not use this file except in compliance with the License.
09: * You may obtain a copy of the License at
10: *
11: * http://www.apache.org/licenses/LICENSE-2.0
12: *
13: * Unless required by applicable law or agreed to in writing, software
14: * distributed under the License is distributed on an "AS IS" BASIS,
15: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16: * See the License for the specific language governing permissions and
17: * limitations under the License.
18: *
19: * Initial developer(s): Nicolas Modrzyk
20: * Contributor(s): ______________________.
21: */package org.continuent.sequoia.common.stream.encoding;
22:
23: /**
24: * This class implements Hexa encoding and decoding
25: *
26: * @author <a href="mailto:Nicolas.Modrzyk@inria.fr">Nicolas Modrzyk </a>
27: * @version 1.0
28: */
29: public class HexaEncoding {
30: /**
31: * Convert data into hexa
32: *
33: * @param data to convert
34: * @return the converted string
35: */
36: public static final String data2hex(byte[] data) {
37: if (data == null)
38: return null;
39:
40: int len = data.length;
41: StringBuffer buf = new StringBuffer(len * 2);
42: for (int pos = 0; pos < len; pos++)
43: buf.append(toHexChar((data[pos] >>> 4) & 0x0F)).append(
44: toHexChar(data[pos] & 0x0F));
45: return buf.toString();
46: }
47:
48: /**
49: * convert hexa into data
50: *
51: * @param str to convert
52: * @return the converted byte array
53: */
54: public static final byte[] hex2data(String str) {
55: if (str == null)
56: return new byte[0];
57:
58: int len = str.length();
59: char[] hex = str.toCharArray();
60: byte[] buf = new byte[len / 2];
61:
62: for (int pos = 0; pos < len / 2; pos++)
63: buf[pos] = (byte) (((toDataNibble(hex[2 * pos]) << 4) & 0xF0) | (toDataNibble(hex[2 * pos + 1]) & 0x0F));
64:
65: return buf;
66: }
67:
68: /**
69: * convert value to hexa value
70: *
71: * @param i byte to convert
72: * @return hexa char
73: */
74: public static char toHexChar(int i) {
75: if ((0 <= i) && (i <= 9))
76: return (char) ('0' + i);
77: else
78: return (char) ('a' + (i - 10));
79: }
80:
81: /**
82: * convert hexa char to byte value
83: *
84: * @param c hexa character
85: * @return corresponding byte value
86: */
87: public static byte toDataNibble(char c) {
88: if (('0' <= c) && (c <= '9'))
89: return (byte) ((byte) c - (byte) '0');
90: else if (('a' <= c) && (c <= 'f'))
91: return (byte) ((byte) c - (byte) 'a' + 10);
92: else if (('A' <= c) && (c <= 'F'))
93: return (byte) ((byte) c - (byte) 'A' + 10);
94: else
95: return -1;
96: }
97: }
|