Skip to content

Instantly share code, notes, and snippets.

@keepingcoding
Created January 8, 2020 08:50
Show Gist options
  • Save keepingcoding/dbb915354f1efab41c8f977f44bfc735 to your computer and use it in GitHub Desktop.
Save keepingcoding/dbb915354f1efab41c8f977f44bfc735 to your computer and use it in GitHub Desktop.

Revisions

  1. keepingcoding created this gist Jan 8, 2020.
    36 changes: 36 additions & 0 deletions HexUtils.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,36 @@
    public class HexUtils {

    private HexUtils() {
    }

    /**
    * 16进制转2进制
    *
    * @param str
    * @return
    */
    public static byte[] hexStrToByte(String str) {
    int length = str.length() / 2;
    byte[] bytes = new byte[length];
    for (int i = 0; i < length; i++) {
    bytes[i] = (byte)((Character.digit(str.charAt(i * 2), 16) << 4) |
    Character.digit(str.charAt((i * 2) + 1), 16));
    }
    return bytes;
    }

    /**
    * 2进制转16进制
    *
    * @param bytes
    * @return
    */
    public static String byteToHexStr(byte[] bytes) {
    StringBuilder buf = new StringBuilder(bytes.length << 1);
    for (byte b : bytes) {
    buf.append(String.format("%02x", new Integer(b & 0xff)));
    }

    return buf.toString();
    }
    }