Hex.java

  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. package org.eclipse.jgit.util;

  11. import java.text.MessageFormat;

  12. import org.eclipse.jgit.internal.JGitText;

  13. /**
  14.  * Encodes and decodes to and from hexadecimal notation.
  15.  *
  16.  * @since 5.7
  17.  */
  18. public final class Hex {

  19.     private static final char[] HEX = "0123456789abcdef".toCharArray(); //$NON-NLS-1$

  20.     /** Defeats instantiation. */
  21.     private Hex() {
  22.         // empty
  23.     }

  24.     /**
  25.      * Decode a hexadecimal string to a byte array.
  26.      *
  27.      * Note this method validates that characters in the given string are valid
  28.      * as digits in a hex string.
  29.      *
  30.      * @param s
  31.      *            hexadecimal string
  32.      * @return decoded array
  33.      */
  34.     public static byte[] decode(String s) {
  35.         int len = s.length();
  36.         byte[] b = new byte[len / 2];

  37.         for (int i = 0; i < len; i += 2) {
  38.             int left = Character.digit(s.charAt(i), 16);
  39.             int right = Character.digit(s.charAt(i + 1), 16);

  40.             if (left == -1 || right == -1) {
  41.                 throw new IllegalArgumentException(MessageFormat.format(
  42.                         JGitText.get().invalidHexString,
  43.                         s));
  44.             }

  45.             b[i / 2] = (byte) (left << 4 | right);
  46.         }
  47.         return b;
  48.     }

  49.     /**
  50.      * Encode a byte array to a hexadecimal string.
  51.      *
  52.      * @param b byte array
  53.      * @return hexadecimal string
  54.      */
  55.     public static String toHexString(byte[] b) {
  56.         char[] c = new char[b.length * 2];

  57.         for (int i = 0; i < b.length; i++) {
  58.             int v = b[i] & 0xFF;

  59.             c[i * 2] = HEX[v >>> 4];
  60.             c[i * 2 + 1] = HEX[v & 0x0F];
  61.         }

  62.         return new String(c);
  63.     }
  64. }