KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > gcc > util > Base16Binary


1 /*
2  * Copyright 2004 The Apache Software Foundation or its licensors, as
3  * applicable.
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
14  * implied.
15  *
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */

19 package gcc.util;
20
21 public class Base16Binary
22 {
23     /**
24      ** Convert from hexadecimal string to byte array.
25      **/

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

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

53     public static String toString(byte[] bytes)
54     {
55         return toString(bytes, 0, bytes.length);
56     }
57
58     /**
59      ** Convert from byte array to hexadecimal string.
60      **/

61     public static String toString(byte[] bytes, int offset, int length)
62     {
63         char[] chars = new char[length * 2];
64         for (int j = 0, k = 0; j < length; j++, k += 2)
65         {
66             int value = (bytes[offset + j] + 256) & 255;
67             chars[k] = Character.forDigit(value >> 4, 16);
68             chars[k + 1] = Character.forDigit(value & 15, 16);
69         }
70         return new String(chars);
71     }
72 }
73
Popular Tags