现在的位置: 首页 > 综合 > 正文

unicode2ascii+ascii2unicode

2013年09月15日 ⁄ 综合 ⁄ 共 1801字 ⁄ 字号 评论关闭

/**
  * 计数,通过位移后和整形变量相与得到结果
  * 0000 0000 is a byte,so move 8 bytes add to new byte[]
  * for example,001a 0001 the new byte[] is {001a,0001}
  * @param byteLen
  * @param a
  * @return
  */
 public byte[] moveBytes(int byteLen,long a){
  byte[] moveTag=new byte[byteLen];
  int j=0;
  for (int i = byteLen-1; i >= 0; i--) {
   //System.out.println("i="+i);
   moveTag[i]=moveByte(a, 8*j);
  // System.out.println("j="+j);
   j=j+1;
  }
  return moveTag;
 }

/**
  * from byte[] which be convertCode to byte[] which be showAbleBytes
  * byte[] length from length to length*2
  * @param b
  * @return
  */
 public byte[] showBytes(byte[] b){
  //String s = new String();
  //char[] ch = new char[b.length*2];
  byte[] newBytes = new byte[b.length*2];
  byte[] oneBytes;
  for (int i = 0; i < b.length; i++) {
    oneBytes = hexToAsc(b[i]);
    newBytes[i*2]=oneBytes[0];
    //ch[i*2]=(char)(oneBytes[0]&0xff);
    newBytes[i*2+1]=oneBytes[1];
    //ch[i*2+1]=(char)(oneBytes[1]&0xff);
   }
  
  return newBytes;
 }

/**
  * new String() maybe cause charset exception,so use getStr to instead of it
  * @param b
  * @return
  */
 public  String getStr(byte[] b){
  String ss = new String();
  for(int i=0; i<b.length; i++)
  {
  
   ss =ss + (char)(b[i]&0xff);
   
  }
  return ss;
 }

/**
  * convert from String to ucs2,for exp:33你好 to 003300334F60597D
  * @param s
  * @return
  */
 public String toUnicodeStr(String s){
  StringBuilder unicodeStr = new StringBuilder();
  for (int i = 0; i < s.length(); i++) {
   //unicodeStr.append(new String(showBytes(moveBytes(2, s.charAt(i)))));
   unicodeStr.append(getStr(showBytes(moveBytes(2, s.charAt(i)))));
  }
  return unicodeStr.toString();
 }
 /**
  * for exp convert "4F60597D" to "你好"
  * convert unicode to ascii
  * @param ascii unicode String
  * @return
  */
 public String unicode2ascii(String ascii){
  StringBuffer buffer = new StringBuffer();
  for (int i = 0; i < ascii.length()/4; i++) {//unicode is 4 bytes
   buffer.append(new Character((char) (Integer.parseInt(ascii.substring(4*i, 4*i+4), 16))));
  }
  return buffer.toString();
 }

抱歉!评论已关闭.