1/*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements.  See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License.  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 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18/*
19Extracted from commons-codec
20 */
21package com.coremedia.iso;
22
23import java.io.ByteArrayOutputStream;
24
25/**
26 * Converts hexadecimal Strings.
27 */
28public class Hex {
29    private static final char[] DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
30
31    public static String encodeHex(byte[] data) {
32        return encodeHex(data, 0);
33    }
34
35    public static String encodeHex(byte[] data, int group) {
36        int l = data.length;
37        char[] out = new char[(l << 1) + (group > 0 ? (l / group) : 0)];
38        // two characters form the hex value.
39        for (int i = 0, j = 0; i < l; i++) {
40            if ((group > 0) && ((i % group) == 0) && j > 0) {
41                out[j++] = '-';
42            }
43
44            out[j++] = DIGITS[(0xF0 & data[i]) >>> 4];
45            out[j++] = DIGITS[0x0F & data[i]];
46        }
47        return new String(out);
48    }
49
50    public static byte[] decodeHex(String hexString) {
51        ByteArrayOutputStream bas = new ByteArrayOutputStream();
52        for (int i = 0; i < hexString.length(); i += 2) {
53            int b = Integer.parseInt(hexString.substring(i, i + 2), 16);
54            bas.write(b);
55        }
56        return bas.toByteArray();
57    }
58}
59