zoukankan      html  css  js  c++  java
  • Java

      做课程设计的时候在处理vCard格式的时候遇到过出现十六进制编码的情况,例如

         QUOTED-PRINTABLE:=XX=XX=XX=XX=XX``````

      其中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 数组的长度。

      先将十六进制转成byte,然后再用String的构造方法生成字符串。

  • 相关阅读:
    一起学Python:协程
    一起学Python:字符串介绍
    一起学Python:列表介绍
    一起学Python:字典介绍
    一起学Python:元组
    函数介绍
    函数参数和函数返回值
    CodeForces 680A&680B&680C&680D Round#356
    POJ 3481 set水过
    BZOJ 1037 生日聚会 DP
  • 原文地址:https://www.cnblogs.com/sineatos/p/3777005.html
Copyright © 2011-2022 走看看