java中 16進制字符串 與普通字符串 與 byte數組 之間的轉化


方法依賴commons-codec包  maven的引入方式如下

1 <dependency>
2    <groupId>commons-codec</groupId>
3    <artifactId>commons-codec</artifactId>
4    <version>1.12</version>
5 </dependency>

 

1. 普通字符串轉換為16進制字符串

 1    /**
 2      * 將普通字符串轉換為16進制字符串
 3      * @param str 普通字符串
 4      * @param lowerCase 轉換后的字母為是否為小寫  可不傳默認為true
 5      * @param charset 編碼格式  可不傳默認為Charset.defaultCharset()
 6      * @return
 7      * @throws UnsupportedEncodingException
 8      */
 9     public static String str2HexStr(String str,boolean lowerCase,String charset) throws UnsupportedEncodingException {
10         return Hex.encodeHexString(str.getBytes(charset),lowerCase);
11     }

 

2.16進制字符串轉換為普通字符串

   /**
     * 將16進制字符串轉換為普通字符串
     * @param hexStr 16進制字符串
     * @param charset 編碼格式 可不傳默認為Charset.defaultCharset()
     * @return
     * @throws DecoderException
     * @throws UnsupportedEncodingException
     */
    public static String hexStr2Str(String hexStr,String charset) throws DecoderException, UnsupportedEncodingException {
        byte[] bytes = Hex.decodeHex(hexStr);
        return new String(bytes,charset);
    }

 

3. 16進制字符串轉換為byte數組

1    /**
2      * 將16進制字符串轉換為byte數組
3      * @param hexItr 16進制字符串
4      * @return
5      */
6     public static byte[] hexItr2Arr(String hexItr) throws DecoderException {
7         return Hex.decodeHex(hexItr);
8     }

 

4. byte數組轉換為16進制字符串

1    /**
2      * byte數組轉化為16進制字符串
3      * @param arr 數組
4      * @param lowerCase 轉換后的字母為是否為小寫 可不傳默認為true
5      * @return
6      */
7     public static String arr2HexStr(byte[] arr,boolean lowerCase){
8         return Hex.encodeHexString(arr, lowerCase);
9     }

 

5. 將普通字符串轉換為指定編碼格式的byte數組

 1    /**
 2      * 將普通字符串轉換為指定格式的byte數組
 3      * @param str 普通字符串
 4      * @param charset 編碼格式 可不傳默認為Charset.defaultCharset()
 5      * @return
 6      * @throws UnsupportedEncodingException
 7      */
 8     public static byte[] str2Arr(String str,String charset) throws UnsupportedEncodingException {
 9         return str.getBytes(charset);
10     }

6. 將byte數組轉換為指定編碼格式的普通字符串

 1     /**
 2      * 將byte數組轉換為指定編碼格式的普通字符串
 3      * @param arr byte數組
 4      * @param charset 編碼格式 可不傳默認為Charset.defaultCharset()
 5      * @return
 6      * @throws UnsupportedEncodingException
 7      */
 8     public static String arr2Str(byte[] arr,String charset) throws UnsupportedEncodingException {
 9         return new String(arr,charset);
10     }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM