笔记_gbk编码互转

  • gbk编码转字符
//测试数据
String encoded = "72746D703A2F2F3131312E3139382E32342E33333A33382F4C312F686F6D6500"; //31

//字符转成字节接受,数据必须为偶数,否则丢失数据
int dataSize = encoded.length()/2;
		byte[] bs = new byte[dataSize];
		for (int i = 0; i < bs.length; i++) {
			bs[i] = (byte) Integer.parseInt(encoded.substring(2*i, 2*i+2), 16);
		}
          String chinese = new String(bs, "GBK");
		
		//输出结果:中文:rtmp://111.198.24.33:38/L1/home
			System.out.println("中文:" + chinese);  
  • 字符转gbk编码
public static String encodeCN(String data) {
		byte[] bytes;
		try {
			bytes = data.getBytes("gbk");
			StringBuilder sb = new StringBuilder(bytes.length * 2);
 
			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();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return "";
	}

//输出结果:72746D703A2F2F3131312E3139382E32342E33333A33382F4C312F686F6D65
System.out.println(encodeCN("rtmp://111.198.24.33:38/L1/home"));

猜你喜欢

转载自blog.csdn.net/DeadlyMouse/article/details/86013120