Java字符和16进制互相转化~

说明:用日文charset  shift-jis(汉字假名占2byte,英文数字占1byte)实现的。
java 代码
 
  1. import java.io.UnsupportedEncodingException;  
  2.   
  3. public class CharStr {  
  4.   
  5.     private static String hex2Str(String theHex) {  
  6.         String theRst = "";  
  7.         byte[] theByte = new byte[theHex.length() / 2];  
  8.   
  9.         try {  
  10.             for (int i = 0; i < theHex.length(); i += 2) {  
  11.                 theByte[i / 2 ] = Integer.decode("0X"+  
  12.                         theHex.substring(i, i + 2)).byteValue();  
  13.             }  
  14.             theRst = new String(theByte, 0, theByte.length, "Shift_JIS");  
  15.         } catch (Exception Ue) {  
  16.             Ue.printStackTrace();  
  17.         }  
  18.         return theRst;  
  19.     }  
  20.   
  21.     private static String str2Hex(String theStr) {  
  22.         byte[] bytes;  
  23.         String result = "";  
  24.         int tmp;  
  25.         String tmpStr;  
  26.         try {  
  27.             bytes = theStr.getBytes("Shift_JIS");  
  28.             for (int i = 0; i < bytes.length; i++) {  
  29.                 if (bytes[i] < 0) {  
  30.                     tmp = 256 + bytes[i];  
  31.                     tmpStr = Integer.toHexString(tmp).toUpperCase();  
  32.                     result += tmpStr;  
  33.                 } else {  
  34.                     tmpStr = Integer.toHexString(bytes[i]).toUpperCase();  
  35.                       
  36.                     result += tmpStr.length()==1?"0"+tmpStr:tmpStr;  
  37.                 }  
  38.             }  
  39.         } catch (UnsupportedEncodingException e) {  
  40.             // TODO Auto-generated catch block  
  41.             e.printStackTrace();  
  42.         }  
  43.         return result;  
  44.     }  
  45.     public static void main(String[] argv) throws UnsupportedEncodingException {  
  46.         String a = "abcdefあaいbうcえdおe";  
  47.         String b = str2Hex(a);  
  48.         String c = hex2Str(b);  
  49.         System.out.println(a);  
  50.         System.out.println(b);  
  51.         System.out.println(c);  
  52.     }  
  53. }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值