進位制轉換的工具類

weixin_34393428發表於2018-09-19
public class HexUtil
{
    /**
     * 16進位制中的字符集
     */
    private static final String HEX_CHAR = "0123456789ABCDEF";

    /**
     * 16進位制中的字符集對應的位元組陣列
     */
    private static final byte[] HEX_STRING_BYTE = HEX_CHAR.getBytes();

    /**
     * 10進位制位元組陣列轉換為16進位制位元組陣列
     * <p>
     * byte用二進位制表示佔用8位,16進位制的每個字元需要用4位二進位制位來表示,則可以把每個byte
     * 轉換成兩個相應的16進位制字元,即把byte的高4位和低4位分別轉換成相應的16進位制字元,再取對應16進位制字元的位元組
     *
     * @param b 10進位制位元組陣列
     * @return 16進位制位元組陣列
     */
    public static byte[] byte2hex(byte[] b)
    {
        int length = b.length;
        byte[] b2 = new byte[length << 1];
        int pos;
        for (int i = 0; i < length; i++) {
            pos = 2 * i;
            b2[pos] = HEX_STRING_BYTE[(b[i] & 0xf0) >> 4];
            b2[pos + 1] = HEX_STRING_BYTE[b[i] & 0x0f];
        }
        return b2;
    }

    /**
     * 16進位制位元組陣列轉換為10進位制位元組陣列
     * <p>
     * 兩個16進位制位元組對應一個10進位制位元組,則將第一個16進位制位元組對應成16進位制字元表中的位置(0~15)並向左移動4位,
     * 再與第二個16進位制位元組對應成16進位制字元表中的位置(0~15)進行或運算,則得到對應的10進位制位元組
     *
     * @param b 10進位制位元組陣列
     * @return 16進位制位元組陣列
     */
    public static byte[] hex2byte(byte[] b)
    {
        if (b.length % 2 != 0) {
            throw new IllegalArgumentException("byte array length is not even!");
        }

        int length = b.length >> 1;
        byte[] b2 = new byte[length];
        int pos;
        for (int i = 0; i < length; i++) {
            pos = i << 1;
            b2[i] = (byte) (HEX_CHAR.indexOf(b[pos]) << 4 | HEX_CHAR.indexOf(b[pos + 1]));
        }
        return b2;
    }

    /**
     * 將16進位制位元組陣列轉成10進位制字串
     *
     * @param b 16進位制位元組陣列
     * @return 10進位制字串
     */
    public static String hex2Str(byte[] b)
    {
        return new String(hex2byte(b));
    }

    /**
     * 將10進位制位元組陣列轉成16進位制字串
     *
     * @param b 10進位制位元組陣列
     * @return 16進位制字串
     */
    public static String byte2HexStr(byte[] b)
    {
        return Integer.toHexString(Integer.parseInt(new String(b)));
    }


    public static byte[] hexString2Bytes(String hex)
    {

        if ((hex == null) || (hex.equals(""))) {
            return null;
        } else if (hex.length() % 2 != 0) {
            return null;
        } else {
            hex = hex.toUpperCase();
            int len = hex.length() / 2;
            byte[] b = new byte[len];
            char[] hc = hex.toCharArray();
            for (int i = 0; i < len; i++) {
                int p = 2 * i;
                b[i] = (byte) (charToByte(hc[p]) << 4 | charToByte(hc[p + 1]));
            }
            return b;
        }
    }

    /*
   * 字元轉換為位元組
   */
    private static byte charToByte(char c)
    {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    /**
     * 位元組陣列轉為普通字串(ASCII對應的字元)
     *
     * @param bytearray byte[]
     * @return String
     */
    public static String bytetoString(byte[] bytearray)
    {
        String result = "";
        char temp;

        int length = bytearray.length;
        for (int i = 0; i < length; i++) {
            temp = (char) bytearray[i];
            result += temp;
        }
        return result;
    }

    /**
     * 數字字串轉ASCII碼字串
     *
     * @param content 字串
     * @return ASCII字串
     */
    public static String StringToAsciiString(String content)
    {
        String result = "";
        int max = content.length();
        for (int i = 0; i < max; i++) {
            char c = content.charAt(i);
            String b = Integer.toHexString(c);
            result = result + b;
        }
        return result;
    }

    /**
     * 十六進位制字串裝十進位制
     *
     * @param hex 十六進位制字串
     * @return 十進位制數值
     */
    public static int hexStringToAlgorism(String hex)
    {
        hex = hex.toUpperCase();
        int max = hex.length();
        int result = 0;
        for (int i = max; i > 0; i--) {
            char c = hex.charAt(i - 1);
            int algorism = 0;
            if (c >= '0' && c <= '9') {
                algorism = c - '0';
            } else {
                algorism = c - 55;
            }
            result += Math.pow(16, max - i) * algorism;
        }
        return result;
    }

    /**
     * ASCII碼字串轉數字字串
     *
     * @param content ASCII字串
     * @return 字串
     */
    public static String AsciiStringToString(String content)
    {
        String result = "";
        int length = content.length() / 2;
        for (int i = 0; i < length; i++) {
            String c = content.substring(i * 2, i * 2 + 2);
            int a = hexStringToAlgorism(c);
            char b = (char) a;
            String d = String.valueOf(b);
            result += d;
        }
        return result;
    }

    /***
     * Ascii轉16進位制
     * @param str
     * @return
     */
    public static String convertStringToHex(String str)
    {

        char[] chars = str.toCharArray();

        StringBuffer hex = new StringBuffer();
        for (int i = 0; i < chars.length; i++) {
            hex.append(Integer.toHexString((byte) chars[i]));
        }
        return hex.toString();
    }

    /***
     * 16進位制轉ASCII
     * @param hex
     * @return
     */
    public static String convertHexToString(String hex)
    {

        StringBuilder sb = new StringBuilder();
        StringBuilder temp = new StringBuilder();

        //49204c6f7665204a617661 split into two characters 49, 20, 4c...
        for (int i = 0; i < hex.length() - 1; i += 2) {

            //grab the hex in pairs
            String output = hex.substring(i, (i + 2));
            //convert hex to decimal
            int decimal = Integer.parseInt(output, 16);
            //convert the decimal to character
            sb.append((char) decimal);

            temp.append(decimal);
        }

        return sb.toString();
    }

    /***
     * byte[] z轉int
     * @param b
     * @return
     */
    public static int bytes2int(byte[] b)
    {
        int mask = 0xff;
        int temp = 0;
        int res = 0;
        for (int i = 0; i < 4; i++) {
            res <<= 8;
            temp = b[i] & mask;
            res |= temp;
        }
        return res;
    }

    public static byte[] int2bytes(int num)
    {
        byte[] b = new byte[4];
        for (int i = 0; i < 4; i++) {
            b[i] = (byte) (num >>> (24 - i * 8));
        }
        return b;
    }

    /**
     * 中文轉Unicode
     *
     * @param gbString
     * @return
     */
    public static String UnicodeEncoding(String gbString)
    {   //gbString = "測試"
        char[] utfBytes = gbString.toCharArray();   //utfBytes = [測, 試]
        String unicodeBytes = "";
        for (int byteIndex = 0; byteIndex < utfBytes.length; byteIndex++) {
            String hexB = Integer.toHexString(utfBytes[byteIndex]);   //轉換為16進位制整型字串
            if (hexB.length() <= 2) {
                hexB = "00" + hexB;
            }
            unicodeBytes = unicodeBytes + "\\u" + hexB;
        }
        return unicodeBytes;
    }

    /**
     * Unicode轉中文
     */
    public static String decodeUnicode(String dataStr)
    {
        int start = 0;
        int end = 0;
        StringBuffer buffer = new StringBuffer();
        while (start > -1) {
            end = dataStr.indexOf("\\u", start + 2);
            String charStr = "";
            if (end == -1) {
                charStr = dataStr.substring(start + 2, dataStr.length());
            } else {
                charStr = dataStr.substring(start + 2, end);
            }
            char letter = (char) Integer.parseInt(charStr, 16); // 16進位制parse整形字串。
            buffer.append(new Character(letter).toString());
            start = end;
        }
        return buffer.toString();
    }


    /**
     * gb2312編碼
     */
    public static String gb2312decode(String string) throws UnsupportedEncodingException
    {
        byte[] bytes = new byte[string.length() / 2];
        for (int i = 0; i < bytes.length; i++) {
            byte high = Byte.parseByte(string.substring(i * 2, i * 2 + 1), 16);
            byte low = Byte.parseByte(string.substring(i * 2 + 1, i * 2 + 2), 16);
            bytes[i] = (byte) (high << 4 | low);
        }
        return new String(bytes, "gb2312");
    }

    /**
     * gb2312解碼
     */
    public static String gb2312eecode(String string) throws UnsupportedEncodingException
    {
        StringBuffer gbkStr = new StringBuffer();
        byte[] gbkDecode = string.getBytes("gb2312");
        for (byte b : gbkDecode) {
            gbkStr.append(Integer.toHexString(b & 0xFF));
        }
        return gbkStr.toString();
    }

 /**
     * 和校驗
     * SUM(cmd, Length, Data0…DataN)^0xFF
     * */
    public static byte getCheckSum(byte[] packBytes){
        int checkSum = 0;

        for (int i = 0; i < packBytes.length; i++) {
            checkSum += packBytes[i];
        }
        checkSum &= 0xff;
        return (byte)checkSum;
    }


}

相關文章