盛 图 主 管 开

盛 图 主 管 【Q和V同:632144】【顶尖待遇一步到位】-注-册-.-充-值-.-代-理-.-开-户,无需打开页面.欢迎随时咨询!做课程设计的时候在处理vCard格式的时候遇到过出现十六进制编码的情况,例如
  QUOTED-PRINTABLE:=XX=XX=XX=XX=XX``````
  盛 图 主 管 【Q和V同:632144 】【顶尖待遇一步到位】-注-册-.-充-值-.-代-理-.-开-户,无需打开页面.欢迎随时咨询!其中XX代表十六进制数,当然,也有可能在末尾跟着非十六进制的字符串(一般是数字)。每一个十六进制数的前面都有一个“=”,那么我们需要怎样处理它才能得到我们需要的字符串呢?
  先看代码:
  1 package Function.Base_Function;
  2
  3 import java.io.UnsupportedEncodingException;
  4
  5 /**
  6 *
  7 * @author Sineatos
  8 */
  9
  10 public class CodeTranslator {
  11 private CodeTranslator(){
  12 }
  13
  14 /**
  15 * 将十六进制编码转化为目标编码
  16 */
  17 public static String HextoString(String string,String CodeName){
  18 String[] Hex;
  19 Hex = string.split("=");
  20 byte[] bytes = new byte[Hex.length-1];
  21 int j=0;
  22 for(int i=1;i<Hex.length;i++){
  23 if(Hex[i].length()>2){
  24 /*如果是非十六进制编码的时候直接将这些编码写进bytes数组*/
  25 byte[] wordsbytes = Hex[i].getBytes();
  26 byte[] newbytes = new byte[bytes.length + wordsbytes.length];
  27 // System.attaycopy(src,srcPos,dest,destPos,length);
  28 System.arraycopy(bytes, 0, newbytes, 0, bytes.length);
  29 System.arraycopy(wordsbytes, 0, newbytes, j, wordsbytes.length);
  30 bytes = newbytes;
  31 j=j+wordsbytes.length;
  32 }else{
  33 Integer hex = Integer.decode("0x" + Hex[i]);
  34 bytes[j] = hex.byteValue();
  35 j++;
  36 }
  37 }
  38 String newstring = null;
  39 try {
  40 newstring = new String(bytes,CodeName);
  41 } catch (UnsupportedEncodingException ex) {
  42 System.out.println("Error in Encoding Vcard");
  43 }
  44 return newstring;
  45 }
  46 }
  这里我们需要用到的是Integer和String。
  public static Integer decode(String nm)
  将 String 解码为 Integer。接受通过以下语法给出的十进制、十六进制和八进制数字
  public String(byte[] bytes,String charsetName)
  通过使用指定的 charset 解码指定的 byte 数组,构造一个新的 String。新 String 的长度是字符集的函数,因此可能不等于 byte 数组的长度。
  盛 图 主 管 【Q和V同:632144 】【顶尖待遇一步到位】-注-册-.-充-值-.-代-理-.-开-户,无需打开页面.欢迎随时咨询!先将十六进制转成byte,然后再用String的构造方法生成字符串。

猜你喜欢

转载自www.cnblogs.com/xiaoxi1314/p/12784084.html