import java.io.ByteArrayOutputStream; /** * Created by Administrator on 2016/2/2. * -----------16進位和字元串互轉--------- * ------------解決中文亂碼問題--------- */
import java.io.ByteArrayOutputStream; /** * Created by Administrator on 2016/2/2. * -----------16進位和字元串互轉--------- * ------------解決中文亂碼問題--------- */ public class StringToSixthUtils { private static String hexString = "0123456789abcdef"; /* * 將字元串編碼成16進位數字,適用於所有字元(包括中文) */ public static String encode(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))); } return sb.toString(); } /* * 將16進位數字解碼成字元串,適用於所有字元(包括中文) */ public static String decode(String bytes) { ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length() / 2); //將每2位16進位整數組裝成一個位元組 for (int i = 0; i < bytes.length(); i += 2) baos.write((hexString.indexOf(bytes.charAt(i)) << 4 | hexString.indexOf(bytes.charAt(i + 1)))); return new String(baos.toByteArray()); } }