- import java.io.ByteArrayOutputStream;
- import java.lang.Character.UnicodeBlock;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- /**
- * 該類處理字符串的轉碼,可以處理字符串到二進制字符、16進制字符、unicode字符、base64字符之間的轉換
- * @author ShaoJiang
- *
- */
- public class TranscodeUtil {
- /**
- * 將字符串轉換成unicode碼
- * @param str 要轉碼的字符串
- * @return 返回轉碼後的字符串
- */
- public static String strToUnicodeStr(String str) {
- StringBuffer buffer = new StringBuffer();
- for (int i = 0; i < str.length(); i++) {
- char ch = str.charAt(i);
- UnicodeBlock ub = UnicodeBlock.of(ch);
- if (ub == UnicodeBlock.BASIC_LATIN) {//英文及數字等
- buffer.append(ch);
- } else if ((int)ch > 255) {
- buffer.append("\\u" + Integer.toHexString((int)ch));
- } else {
- buffer.append("\\" + Integer.toHexString((int)ch));
- }
- }
- return buffer.toString();
- }
- /**
- * 將unicode碼反轉成字符串
- * @param unicodeStr unicode碼
- * @return 返回轉碼後的字符串
- */
- public static String unicodeStrToStr(String unicodeStr) {
- Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
- Matcher matcher = pattern.matcher(unicodeStr);
- char ch;
- while (matcher.find()) {
- ch = (char) Integer.parseInt(matcher.group(2), 16);
- unicodeStr = unicodeStr.replace(matcher.group(1), ch + "");
- }
- return unicodeStr;
- }
- /**
- * 將字符串通過base64轉碼
- * @param str 要轉碼的字符串
- * @return 返回轉碼後的字符串
- */
- public static String strToBase64Str(String str) {
- return new String(encode(str.getBytes()));
- }
- /**
- * 將base64碼反轉成字符串
- * @param base64Str base64碼
- * @return 返回轉碼後的字符串
- */
- public static String base64StrToStr(String base64Str) {
- char[] dataArr = new char[base64Str.length()];
- base64Str.getChars(0, base64Str.length(), dataArr, 0);
- return new String(decode(dataArr));
- }
- /**
- * 將字節數組通過base64轉碼
- * @param byteArray 字節數組
- * @return 返回轉碼後的字符串
- */
- public static String byteArrayToBase64Str(byte byteArray[]) {
- return new String(encode(byteArray));
- }
- /**
- * 將base64碼轉換成字節數組
- * @param base64Str base64碼
- * @return 返回轉換後的字節數組
- */
- public static byte[] base64StrToByteArray(String base64Str) {
- char[] dataArr = new char[base64Str.length()];
- base64Str.getChars(0, base64Str.length(), dataArr, 0);
- return decode(dataArr);
- }
- /**
- * 將一個字節數組轉換成base64的字符數組
- * @param data 字節數組
- * @return base64字符數組
- */
- private static char[] encode(byte[] data) {
- char[] out = new char[((data.length + 2) / 3) * 4];
- for (int i = 0, index = 0; i < data.length; i += 3, index += 4) {
- boolean quad = false;
- boolean trip = false;
- int val = (0xFF & (int) data[i]);
- val <<= 8;
- if ((i + 1) < data.length) {
- val |= (0xFF & (int) data[i + 1]);
- trip = true;
- }
- val <<= 8;
- if ((i + 2) < data.length) {
- val |= (0xFF & (int) data[i + 2]);
- quad = true;
- }
- out[index + 3] = alphabet[(quad ? (val & 0x3F) : 64)];
- val >>= 6;
- out[index + 2] = alphabet[(trip ? (val & 0x3F) : 64)];
- val >>= 6;
- out[index + 1] = alphabet[val & 0x3F];
- val >>= 6;
- out[index + 0] = alphabet[val & 0x3F];
- }
- return out;
- }
- /**
- * 將一個base64字符數組解碼成一個字節數組
- * @param data base64字符數組
- * @return 返回解碼以後的字節數組
- */
- private static byte[] decode(char[] data) {
- int len = ((data.length + 3) / 4) * 3;
- if (data.length > 0 && data[data.length - 1] == '=') --len;
- if (data.length > 1 && data[data.length - 2] == '=') --len;
- byte[] out = new byte[len];
- int shift = 0;
- int accum = 0;
- int index = 0;
- for (int ix = 0; ix < data.length; ix++) {
- int value = codes[data[ix] & 0xFF];
- if (value >= 0) {
- accum <<= 6;
- shift += 6;
- accum |= value;
- if (shift >= 8) {
- shift -= 8;
- out[index++] = (byte) ((accum >> shift) & 0xff);
- }
- }
- }
- if (index != out.length)
- throw new Error("miscalculated data length!");
- return out;
- }
- /**
- * base64字符集 0..63
- */
- static private char[] alphabet =
- "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
- .toCharArray();
- /**
- * 初始化base64字符集表
- */
- static private byte[] codes = new byte[256];
- static {
- for (int i = 0; i < 256; i++) codes[i] = -1;
- for (int i = 'A'; i <= 'Z'; i++) codes[i] = (byte) (i - 'A');
- for (int i = 'a'; i <= 'z'; i++) codes[i] = (byte) (26 + i - 'a');
- for (int i = '0'; i <= '9'; i++) codes[i] = (byte) (52 + i - '0');
- codes['+'] = 62;
- codes['/'] = 63;
- }
- /**
- * 16進制數字字符集
- */
- private static String hexString = "0123456789ABCDEF";
- /**
- * 將字符串編碼成16進制數字,適用於所有字符(包括中文)
- * @param str 字符串
- * @return 返回16進制字符串
- */
- public static String strToHexStr(String str) {
- // 根據默認編碼獲取字節數組
- byte[] bytes = str.getBytes();
- StringBuilder sb = new StringBuilder(bytes.length * 2);
- // 將字節數組中每個字節拆解成2位16進制整數
- for (int i = 0; i < bytes.length; i++) {
- sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));
- sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));
- }
- return sb.toString();
- }
- /**
- * 將16進制數字解碼成字符串,適用於所有字符(包括中文)
- * @param hexStr 16進制字符串
- * @return 返回字符串
- */
- public static String hexStrToStr(String hexStr) {
- ByteArrayOutputStream baos = new ByteArrayOutputStream(
- hexStr.length() / 2);
- // 將每2位16進制整數組裝成一個字節
- for (int i = 0; i < hexStr.length(); i += 2)
- baos.write((hexString.indexOf(hexStr.charAt(i)) << 4 | hexString
- .indexOf(hexStr.charAt(i + 1))));
- return new String(baos.toByteArray());
- }
- /**
- * 將字節數組轉換成16進制字符串
- * @param byteArray 要轉碼的字節數組
- * @return 返回轉碼後的16進制字符串
- */
- public static String byteArrayToHexStr(byte byteArray[]) {
- StringBuffer buffer = new StringBuffer(byteArray.length * 2);
- int i;
- for (i = 0; i < byteArray.length; i++) {
- if (((int) byteArray[i] & 0xff) < 0x10)//小於十前面補零
- buffer.append("0");
- buffer.append(Long.toString((int) byteArray[i] & 0xff, 16));
- }
- return buffer.toString();
- }
- /**
- * 將16進制字符串轉換成字節數組
- * @param hexStr 要轉換的16進制字符串
- * @return 返回轉碼後的字節數組
- */
- public static byte[] hexStrToByteArray(String hexStr) {
- if (hexStr.length() < 1)
- return null;
- byte[] encrypted = new byte[hexStr.length() / 2];
- for (int i = 0; i < hexStr.length() / 2; i++) {
- int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);//取高位字節
- int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);//取低位字節
- encrypted[i] = (byte) (high * 16 + low);
- }
- return encrypted;
- }
- /**
- * 將字符串轉換成二進制字符串,以空格相隔
- * @param str 字符串
- * @return 返回二進制字符串
- */
- public static String strToBinStr(String str) {
- char[] chars=str.toCharArray();
- StringBuffer result = new StringBuffer();
- for(int i=0; i<chars.length; i++) {
- result.append(Integer.toBinaryString(chars[i]));
- result.append(" ");
- }
- return result.toString();
- }
- /**
- * 將二進制字符串轉換成Unicode字符串
- * @param binStr 二進制字符串
- * @return 返回字符串
- */
- public static String binStrToStr(String binStr) {
- String[] tempStr=strToStrArray(binStr);
- char[] tempChar=new char[tempStr.length];
- for(int i=0; i<tempStr.length; i++) {
- tempChar[i]=binstrToChar(tempStr[i]);
- }
- return String.valueOf(tempChar);
- }
- /**
- * 將二進制字符串轉換爲char
- * @param binStr 二進制字符串
- * @return 返回字符
- */
- private static char binstrToChar(String binStr) {
- int[] temp=binstrToIntArray(binStr);
- int sum=0;
- for(int i=0; i<temp.length; i++) {
- sum += temp[temp.length-1-i]<<i;
- }
- return (char)sum;
- }
- /**
- * 將初始二進制字符串轉換成字符串數組,以空格相隔
- * @param str 二進制字符串
- * @return 返回字符串數組
- */
- private static String[] strToStrArray(String str) {
- return str.split(" ");
- }
- /**
- * 將二進制字符串轉換成int數組
- * @param binStr 二進制字符串
- * @return 返回int數組
- */
- private static int[] binstrToIntArray(String binStr) {
- char[] temp=binStr.toCharArray();
- int[] result=new int[temp.length];
- for(int i=0; i<temp.length; i++) {
- result[i]=temp[i]-48;
- }
- return result;
- }
- }
java:實現字符串到二進制字符、16進制字符、unicode字符、base64字符之間的轉換
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.