Java byte和hex十六進制字符串轉換


在Java中字符串由字符char組成, 一個char由兩個byte組成, 而一個byte由八個bit組成, 一個十六進制字符(0-F)實際上由4個字節byte即可表達, 因此, 從字節數組到十六進制字符串, 實際上占用的存儲空間擴大了4倍。

 

下面來看一下從十六進制字符串轉換為字節數組的方式:

第一種方法: 實際借用了Character類的方法進行16進制的轉換

 1         static byte[] hexToByteArray2(String hex)
 2     {
 3         int l = hex.length();
 4         byte[] data = new byte[l / 2];
 5         for (int i = 0; i < l; i += 2)
 6         {
 7             data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
 8                     + Character.digit(hex.charAt(i + 1), 16));
 9         }
10         return data;
11     }

 

第二種方法: 借用了Integer類中的十六進制轉換:

1     static byte[] hexToByteArray(String hexString) {
2         byte[] result = new byte[hexString.length() / 2];
3         for (int len = hexString.length(), index = 0; index <= len - 1; index += 2) {
4             String subString = hexString.substring(index, index + 2);
5             int intValue = Integer.parseInt(subString, 16);
6             result[index / 2] = (byte)intValue;
7         }
8         return result;
9     }

 

 

從字節數組轉換為十六進制的方法:

一、

 1     static String byteArrayToHex(byte[] bytes) {
 2         StringBuilder result = new StringBuilder();
 3         for (int index = 0, len = bytes.length; index <= len - 1; index += 1) {
 4             int char1 = ((bytes[index] >> 4) & 0xF);
 5             char chara1 = Character.forDigit(char1, 16);
 6             int char2 = ((bytes[index]) & 0xF);
 7             char chara2 = Character.forDigit(char2, 16);
 8             result.append(chara1);
 9             result.append(chara2);
10         }
11         return result.toString();
12     }

 

二、

 1     static String byteArrayToHex2(byte[] bytes) {
 2         StringBuilder result = new StringBuilder();
 3         for (int index = 0, len = bytes.length; index <= len - 1; index += 1) {
 4 
 5             String invalue1 = Integer.toHexString((bytes[index] >> 4) & 0xF);
 6             String intValue2 = Integer.toHexString(bytes[index] & 0xF);
 7             result.append(invalue1);
 8             result.append(intValue2);
 9         }
10         return result.toString();
11     }

 

然后介紹一種更實用的字符串和十六進制之間的轉換:

十六進制轉字符串:

1     static String hexToString(String hex, Charset charset) {
2         return new String(new BigInteger(hex, 16).toByteArray(), charset);
3     }

 

字符串轉十六進制:

1     static String stringToHex(String arg, Charset charset) {
2         if (arg == null || arg.length() == 0) {
3             return "";
4         }
5         byte[] bytes = arg.getBytes(charset);
6         return String.format("%0" + bytes.length * 2 + "x", new BigInteger(1, bytes));
7     }

 

 

 

 


免責聲明!

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



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