KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > geronimo > interop > util > Base16Binary


1 /**
2  *
3  * Copyright 2004-2005 The Apache Software Foundation
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */

18 package org.apache.geronimo.interop.util;
19
20 public class Base16Binary {
21     /**
22      * * Convert from hexadecimal string to byte array.
23      */

24     public static byte[] fromString(String JavaDoc string) {
25         return fromString(string, 0, string.length());
26     }
27
28     /**
29      * * Convert from hexadecimal string to byte array.
30      */

31     public static byte[] fromString(String JavaDoc string, int offset, int length) {
32         byte[] bytes = new byte[length / 2];
33         for (int j = 0, k = 0; k < length; j++, k += 2) {
34             int hi = Character.digit(string.charAt(offset + k), 16);
35             int lo = Character.digit(string.charAt(offset + k + 1), 16);
36             if (hi == -1 || lo == -1) {
37                 throw new IllegalArgumentException JavaDoc(string);
38             }
39             bytes[j] = (byte) (16 * hi + lo);
40         }
41         return bytes;
42     }
43
44     /**
45      * * Convert from byte array to hexadecimal string.
46      */

47     public static String JavaDoc toString(byte[] bytes) {
48         return toString(bytes, 0, bytes.length);
49     }
50
51     /**
52      * * Convert from byte array to hexadecimal string.
53      */

54     public static String JavaDoc toString(byte[] bytes, int offset, int length) {
55         char[] chars = new char[length * 2];
56         for (int j = 0, k = 0; j < length; j++, k += 2) {
57             int value = (bytes[offset + j] + 256) & 255;
58             chars[k] = Character.forDigit(value >> 4, 16);
59             chars[k + 1] = Character.forDigit(value & 15, 16);
60         }
61         return new String JavaDoc(chars);
62     }
63 }
64
Popular Tags