Chinese characters to hexadecimal method

package com.chen.util;

import java.io.UnsupportedEncodingException;

public class Util {
	
	

public static void main(String args[]){
	String gbk16 = convertStringToUTF8("The weather is nice today","UTF-8");
	System.out.println( gbk16);
	System.out.println(convertUTF8ToString(gbk16,"UTF-8"));
//	BDF1CCECCCECC6F8D5E6BAC3
}



	/**
	 * UTF-8 encoding is converted to the corresponding Chinese characters
	 *
	 * URLEncoder.encode("上海", "UTF-8") ---> %E4%B8%8A%E6%B5%B7
	 * URLDecoder.decode("%E4%B8%8A%E6%B5%B7", "UTF-8") --> 上 海
	 *
	 * convertUTF8ToString("E4B88AE6B5B7")
	 * E4B88AE6B5B7 --> Shanghai
	 *
	 * @param s string
	 * @param Encoder encoding format
	 * @return
	 */
	public static String convertUTF8ToString(String s,String Encoder) {
		if (s == null || s.equals("")) {
			return null;
		}
		
		try {
			s = s.toUpperCase();

			int total = s.length() / 2;
			int pos = 0;

			byte[] buffer = new byte[total];
			for (int i = 0; i < total; i++) {

				int start = i * 2;

				buffer[i] = (byte) Integer.parseInt(
						s.substring(start, start + 2), 16);
				pos++;
			}

			return new String(buffer, 0, pos, Encoder);
			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace ();
		}
		return s;
	}

	/**
	 * Convert the Chinese characters in the file name to UTF8 encoded strings, so that the saved file name can be displayed correctly when downloading.
	 *
	 * @param s original string
	 * @param Encoder encoding format
	 * @return
	 */
	public static String convertStringToUTF8(String s,String Encoder) {
		if (s == null || s.equals("")) {
			return null;
		}
		StringBuffer sb = new StringBuffer();
		try {
			char c;
			for (int i = 0; i < s.length(); i++) {
				c = s.charAt(i);
				if (c >= 0 && c <= 255) {
					sb.append(c);
				} else {
					byte[] b;

					b = Character.toString(c).getBytes(Encoder);

					for (int j = 0; j < b.length; j++) {
						int k = b[j];
						if (k < 0)
							k += 256;
						sb.append(Integer.toHexString(k).toUpperCase());
						// sb.append("%" +Integer.toHexString(k).toUpperCase());
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace ();

		}
		return sb.toString();
	}
}

 

code show as below

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327064659&siteId=291194637