加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

java汉字与UTF-8十六进制编码间相互转换方法

(2019-03-01 08:35:34)
标签:

it

最近项目中需要把中文转换为UTF-8编码,并且还能将转换后的UTF-8编码转换为原来的中文,比如 上海 转换为UTF-8编码为 E4B88AE6B5B7,

Google了不少时间,然后参考 JDK源码 实现了上述功能

代码如下:


 

[java] view plain copy
  1.   
  2.     public static String convertUTF8ToString(String s)  
  3.         if (s == null || s.equals(""))  
  4.             return null 
  5.          
  6.           
  7.         try  
  8.             s.toUpperCase();  
  9.   
  10.             int total s.length() 2 
  11.             int pos 0 
  12.   
  13.             byte[] buffer new byte[total];  
  14.             for (int 0total; i++)  
  15.   
  16.                 int start 2 
  17.   
  18.                 buffer[i] (byteInteger.parseInt(  
  19.                         s.substring(start, start 2), 16);  
  20.                 pos++;  
  21.              
  22.   
  23.             return new String(buffer, 0pos, "UTF-8");  
  24.               
  25.         catch (UnsupportedEncodingException e)  
  26.             e.printStackTrace();  
  27.          
  28.         return s;  
  29.      
  30.   
  31.       
  32.     public static String convertStringToUTF8(String s)  
  33.         if (s == null || s.equals(""))  
  34.             return null 
  35.          
  36.         StringBuffer sb new StringBuffer();  
  37.         try  
  38.             char c;  
  39.             for (int 0s.length(); i++)  
  40.                 s.charAt(i);  
  41.                 if (c >= 0 && <= 255 
  42.                     sb.append(c);  
  43.                 else  
  44.                     byte[] b;  
  45.   
  46.                     Character.toString(c).getBytes("utf-8");  
  47.   
  48.                     for (int 0b.length; j++)  
  49.                         int b[j];  
  50.                         if (k 0 
  51.                             += 256 
  52.                         sb.append(Integer.toHexString(k).toUpperCase());  
  53.                         // sb.append("%" +Integer.toHexString(k).toUpperCase());  
  54.                      
  55.                  
  56.              
  57.         catch (Exception e)  
  58.             e.printStackTrace();  
  59.   
  60.          
  61.         return sb.toString();  
  62.      

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有