java:實現字符串到二進制字符、16進制字符、unicode字符、base64字符之間的轉換

  1. import java.io.ByteArrayOutputStream;  
  2. import java.lang.Character.UnicodeBlock;  
  3. import java.util.regex.Matcher;  
  4. import java.util.regex.Pattern;  
  5.   
  6. /** 
  7.  * 該類處理字符串的轉碼,可以處理字符串到二進制字符、16進制字符、unicode字符、base64字符之間的轉換 
  8.  * @author ShaoJiang 
  9.  * 
  10.  */  
  11. public class TranscodeUtil {  
  12.   
  13.     /** 
  14.      * 將字符串轉換成unicode碼 
  15.      * @param str 要轉碼的字符串 
  16.      * @return 返回轉碼後的字符串 
  17.      */  
  18.     public static String strToUnicodeStr(String str) {  
  19.         StringBuffer buffer = new StringBuffer();  
  20.         for (int i = 0; i < str.length(); i++) {  
  21.             char ch = str.charAt(i);  
  22.             UnicodeBlock ub = UnicodeBlock.of(ch);  
  23.             if (ub == UnicodeBlock.BASIC_LATIN) {//英文及數字等  
  24.                 buffer.append(ch);  
  25.             } else if ((int)ch > 255) {  
  26.                 buffer.append("\\u" + Integer.toHexString((int)ch));  
  27.             } else {  
  28.                 buffer.append("\\" + Integer.toHexString((int)ch));  
  29.             }  
  30.         }  
  31.         return buffer.toString();  
  32.     }  
  33.   
  34.     /** 
  35.      * 將unicode碼反轉成字符串 
  36.      * @param unicodeStr unicode碼 
  37.      * @return 返回轉碼後的字符串 
  38.      */  
  39.     public static String unicodeStrToStr(String unicodeStr) {  
  40.         Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");  
  41.         Matcher matcher = pattern.matcher(unicodeStr);  
  42.         char ch;  
  43.         while (matcher.find()) {  
  44.             ch = (char) Integer.parseInt(matcher.group(2), 16);  
  45.             unicodeStr = unicodeStr.replace(matcher.group(1), ch + "");  
  46.         }  
  47.         return unicodeStr;  
  48.     }  
  49.   
  50.     /** 
  51.      * 將字符串通過base64轉碼 
  52.      * @param str 要轉碼的字符串 
  53.      * @return 返回轉碼後的字符串 
  54.      */  
  55.     public static String strToBase64Str(String str) {  
  56.         return new String(encode(str.getBytes()));  
  57.     }  
  58.   
  59.     /** 
  60.      * 將base64碼反轉成字符串 
  61.      * @param base64Str base64碼 
  62.      * @return 返回轉碼後的字符串 
  63.      */  
  64.     public static String base64StrToStr(String base64Str) {  
  65.         char[] dataArr = new char[base64Str.length()];  
  66.         base64Str.getChars(0, base64Str.length(), dataArr, 0);  
  67.         return new String(decode(dataArr));  
  68.     }  
  69.   
  70.     /** 
  71.      * 將字節數組通過base64轉碼 
  72.      * @param byteArray 字節數組 
  73.      * @return 返回轉碼後的字符串 
  74.      */  
  75.     public static String byteArrayToBase64Str(byte byteArray[]) {  
  76.         return new String(encode(byteArray));  
  77.     }  
  78.   
  79.     /** 
  80.      * 將base64碼轉換成字節數組 
  81.      * @param base64Str base64碼 
  82.      * @return 返回轉換後的字節數組 
  83.      */  
  84.     public static byte[] base64StrToByteArray(String base64Str) {  
  85.         char[] dataArr = new char[base64Str.length()];  
  86.         base64Str.getChars(0, base64Str.length(), dataArr, 0);  
  87.         return decode(dataArr);  
  88.     }  
  89.   
  90.     /** 
  91.      * 將一個字節數組轉換成base64的字符數組 
  92.      * @param data 字節數組 
  93.      * @return base64字符數組 
  94.      */  
  95.     private static char[] encode(byte[] data) {  
  96.         char[] out = new char[((data.length + 2) / 3) * 4];  
  97.         for (int i = 0, index = 0; i < data.length; i += 3, index += 4) {  
  98.             boolean quad = false;  
  99.             boolean trip = false;  
  100.             int val = (0xFF & (int) data[i]);  
  101.             val <<= 8;  
  102.             if ((i + 1) < data.length) {  
  103.                 val |= (0xFF & (int) data[i + 1]);  
  104.                 trip = true;  
  105.             }  
  106.             val <<= 8;  
  107.             if ((i + 2) < data.length) {  
  108.                 val |= (0xFF & (int) data[i + 2]);  
  109.                 quad = true;  
  110.             }  
  111.             out[index + 3] = alphabet[(quad ? (val & 0x3F) : 64)];  
  112.             val >>= 6;  
  113.             out[index + 2] = alphabet[(trip ? (val & 0x3F) : 64)];  
  114.             val >>= 6;  
  115.             out[index + 1] = alphabet[val & 0x3F];  
  116.             val >>= 6;  
  117.             out[index + 0] = alphabet[val & 0x3F];  
  118.         }  
  119.         return out;  
  120.     }  
  121.   
  122.     /** 
  123.      * 將一個base64字符數組解碼成一個字節數組 
  124.      * @param data base64字符數組 
  125.      * @return 返回解碼以後的字節數組 
  126.      */  
  127.     private static byte[] decode(char[] data) {  
  128.         int len = ((data.length + 3) / 4) * 3;  
  129.         if (data.length > 0 && data[data.length - 1] == '=') --len;  
  130.         if (data.length > 1 && data[data.length - 2] == '=') --len;  
  131.         byte[] out = new byte[len];  
  132.         int shift = 0;  
  133.         int accum = 0;  
  134.         int index = 0;  
  135.         for (int ix = 0; ix < data.length; ix++) {  
  136.             int value = codes[data[ix] & 0xFF];  
  137.             if (value >= 0) {  
  138.                 accum <<= 6;  
  139.                 shift += 6;  
  140.                 accum |= value;  
  141.                 if (shift >= 8) {  
  142.                     shift -= 8;  
  143.                     out[index++] = (byte) ((accum >> shift) & 0xff);  
  144.                 }  
  145.             }  
  146.         }  
  147.         if (index != out.length)  
  148.             throw new Error("miscalculated data length!");  
  149.         return out;  
  150.     }  
  151.   
  152.     /** 
  153.      * base64字符集 0..63 
  154.      */  
  155.     static private char[] alphabet =  
  156.         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="  
  157.         .toCharArray();  
  158.   
  159.     /** 
  160.      * 初始化base64字符集表 
  161.      */  
  162.     static private byte[] codes = new byte[256];  
  163.   
  164.     static {  
  165.         for (int i = 0; i < 256; i++) codes[i] = -1;  
  166.         for (int i = 'A'; i <= 'Z'; i++) codes[i] = (byte) (i - 'A');  
  167.         for (int i = 'a'; i <= 'z'; i++) codes[i] = (byte) (26 + i - 'a');  
  168.         for (int i = '0'; i <= '9'; i++) codes[i] = (byte) (52 + i - '0');  
  169.         codes['+'] = 62;  
  170.         codes['/'] = 63;  
  171.     }  
  172.   
  173.     /** 
  174.      * 16進制數字字符集 
  175.      */  
  176.     private static String hexString = "0123456789ABCDEF";  
  177.   
  178.     /** 
  179.      * 將字符串編碼成16進制數字,適用於所有字符(包括中文) 
  180.      * @param str 字符串 
  181.      * @return 返回16進制字符串 
  182.      */  
  183.     public static String strToHexStr(String str) {  
  184.         // 根據默認編碼獲取字節數組  
  185.         byte[] bytes = str.getBytes();  
  186.         StringBuilder sb = new StringBuilder(bytes.length * 2);  
  187.         // 將字節數組中每個字節拆解成2位16進制整數  
  188.         for (int i = 0; i < bytes.length; i++) {  
  189.             sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));  
  190.             sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));  
  191.         }  
  192.         return sb.toString();  
  193.     }  
  194.   
  195.     /** 
  196.      * 將16進制數字解碼成字符串,適用於所有字符(包括中文) 
  197.      * @param hexStr 16進制字符串 
  198.      * @return 返回字符串 
  199.      */  
  200.     public static String hexStrToStr(String hexStr) {  
  201.         ByteArrayOutputStream baos = new ByteArrayOutputStream(  
  202.             hexStr.length() / 2);  
  203.         // 將每2位16進制整數組裝成一個字節  
  204.         for (int i = 0; i < hexStr.length(); i += 2)  
  205.             baos.write((hexString.indexOf(hexStr.charAt(i)) << 4 | hexString  
  206.                         .indexOf(hexStr.charAt(i + 1))));  
  207.         return new String(baos.toByteArray());  
  208.     }  
  209.   
  210.     /** 
  211.      * 將字節數組轉換成16進制字符串 
  212.      * @param byteArray 要轉碼的字節數組 
  213.      * @return 返回轉碼後的16進制字符串 
  214.      */  
  215.     public static String byteArrayToHexStr(byte byteArray[]) {  
  216.         StringBuffer buffer = new StringBuffer(byteArray.length * 2);  
  217.         int i;  
  218.         for (i = 0; i < byteArray.length; i++) {  
  219.             if (((int) byteArray[i] & 0xff) < 0x10)//小於十前面補零  
  220.                 buffer.append("0");  
  221.             buffer.append(Long.toString((int) byteArray[i] & 0xff16));  
  222.         }  
  223.         return buffer.toString();  
  224.     }  
  225.   
  226.     /** 
  227.      * 將16進制字符串轉換成字節數組 
  228.      * @param hexStr 要轉換的16進制字符串 
  229.      * @return 返回轉碼後的字節數組 
  230.      */  
  231.     public static byte[] hexStrToByteArray(String hexStr) {  
  232.         if (hexStr.length() < 1)  
  233.             return null;  
  234.         byte[] encrypted = new byte[hexStr.length() / 2];  
  235.         for (int i = 0; i < hexStr.length() / 2; i++) {  
  236.             int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);//取高位字節  
  237.             int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);//取低位字節  
  238.             encrypted[i] = (byte) (high * 16 + low);  
  239.         }  
  240.         return encrypted;  
  241.     }  
  242.   
  243.     /** 
  244.      * 將字符串轉換成二進制字符串,以空格相隔 
  245.      * @param str 字符串 
  246.      * @return 返回二進制字符串 
  247.      */  
  248.     public static String strToBinStr(String str) {  
  249.         char[] chars=str.toCharArray();  
  250.         StringBuffer result = new StringBuffer();  
  251.         for(int i=0; i<chars.length; i++) {  
  252.             result.append(Integer.toBinaryString(chars[i]));  
  253.             result.append(" ");  
  254.         }  
  255.         return result.toString();  
  256.     }  
  257.   
  258.     /** 
  259.      * 將二進制字符串轉換成Unicode字符串 
  260.      * @param binStr 二進制字符串 
  261.      * @return 返回字符串 
  262.      */  
  263.     public static String binStrToStr(String binStr) {  
  264.         String[] tempStr=strToStrArray(binStr);  
  265.         char[] tempChar=new char[tempStr.length];  
  266.         for(int i=0; i<tempStr.length; i++) {  
  267.             tempChar[i]=binstrToChar(tempStr[i]);  
  268.         }  
  269.         return String.valueOf(tempChar);  
  270.     }  
  271.   
  272.     /** 
  273.      * 將二進制字符串轉換爲char 
  274.      * @param binStr 二進制字符串 
  275.      * @return 返回字符 
  276.      */  
  277.     private static char binstrToChar(String binStr) {  
  278.         int[] temp=binstrToIntArray(binStr);  
  279.         int sum=0;  
  280.         for(int i=0; i<temp.length; i++) {  
  281.             sum += temp[temp.length-1-i]<<i;  
  282.         }  
  283.         return (char)sum;  
  284.     }  
  285.   
  286.     /** 
  287.      * 將初始二進制字符串轉換成字符串數組,以空格相隔 
  288.      * @param str 二進制字符串 
  289.      * @return 返回字符串數組 
  290.      */  
  291.     private static String[] strToStrArray(String str) {  
  292.         return str.split(" ");  
  293.     }  
  294.   
  295.     /** 
  296.      * 將二進制字符串轉換成int數組 
  297.      * @param binStr 二進制字符串 
  298.      * @return 返回int數組 
  299.      */  
  300.     private static int[] binstrToIntArray(String binStr) {  
  301.         char[] temp=binStr.toCharArray();  
  302.         int[] result=new int[temp.length];  
  303.         for(int i=0; i<temp.length; i++) {  
  304.             result[i]=temp[i]-48;  
  305.         }  
  306.         return result;  
  307.     }  
  308. }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章