View Javadoc
1   /*
2    * Copyright (C) 2020, Michael Dardis. and others
3    *
4    * This program and the accompanying materials are made available under the
5    * terms of the Eclipse Distribution License v. 1.0 which is available at
6    * https://www.eclipse.org/org/documents/edl-v10.php.
7    *
8    * SPDX-License-Identifier: BSD-3-Clause
9    */
10  
11  package org.eclipse.jgit.util;
12  
13  import java.text.MessageFormat;
14  
15  import org.eclipse.jgit.internal.JGitText;
16  
17  /**
18   * Encodes and decodes to and from hexadecimal notation.
19   *
20   * @since 5.7
21   */
22  public final class Hex {
23  
24  	private static final char[] HEX = "0123456789abcdef".toCharArray(); //$NON-NLS-1$
25  
26  	/** Defeats instantiation. */
27  	private Hex() {
28  		// empty
29  	}
30  
31  	/**
32  	 * Decode a hexadecimal string to a byte array.
33  	 *
34  	 * Note this method validates that characters in the given string are valid
35  	 * as digits in a hex string.
36  	 *
37  	 * @param s
38  	 *            hexadecimal string
39  	 * @return decoded array
40  	 */
41  	public static byte[] decode(String s) {
42  		int len = s.length();
43  		byte[] b = new byte[len / 2];
44  
45  		for (int i = 0; i < len; i += 2) {
46  			int left = Character.digit(s.charAt(i), 16);
47  			int right = Character.digit(s.charAt(i + 1), 16);
48  
49  			if (left == -1 || right == -1) {
50  				throw new IllegalArgumentException(MessageFormat.format(
51  						JGitText.get().invalidHexString,
52  						s));
53  			}
54  
55  			b[i / 2] = (byte) (left << 4 | right);
56  		}
57  		return b;
58  	}
59  
60  	/**
61  	 * Encode a byte array to a hexadecimal string.
62  	 *
63  	 * @param b byte array
64  	 * @return hexadecimal string
65  	 */
66  	public static String toHexString(byte[] b) {
67  		char[] c = new char[b.length * 2];
68  
69  		for (int i = 0; i < b.length; i++) {
70  			int v = b[i] & 0xFF;
71  
72  			c[i * 2] = HEX[v >>> 4];
73  			c[i * 2 + 1] = HEX[v & 0x0F];
74  		}
75  
76  		return new String(c);
77  	}
78  }