Hex.java 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package com.uas.utils;
  2. public final class Hex {
  3. private static final char[] HEX = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
  4. public static char[] encode(byte[] bytes) {
  5. int nBytes = bytes.length;
  6. char[] result = new char[2 * nBytes];
  7. int j = 0;
  8. for (int i = 0; i < nBytes; ++i) {
  9. result[(j++)] = HEX[((0xF0 & bytes[i]) >>> 4)];
  10. result[(j++)] = HEX[(0xF & bytes[i])];
  11. }
  12. return result;
  13. }
  14. public static byte[] decode(CharSequence s) {
  15. int nChars = s.length();
  16. if (nChars % 2 != 0) {
  17. throw new IllegalArgumentException("Hex-encoded string must have an even number of characters");
  18. }
  19. byte[] result = new byte[nChars / 2];
  20. for (int i = 0; i < nChars; i += 2) {
  21. int msb = Character.digit(s.charAt(i), 16);
  22. int lsb = Character.digit(s.charAt(i + 1), 16);
  23. if ((msb < 0) || (lsb < 0)) {
  24. throw new IllegalArgumentException("Non-hex character in input: " + s);
  25. }
  26. result[(i / 2)] = (byte) (msb << 4 | lsb);
  27. }
  28. return result;
  29. }
  30. }