1. 程式人生 > >Byte[]和BASE64之間的轉換操作

Byte[]和BASE64之間的轉換操作

 Byte[]和BASE64之間的轉換操作

(1)


static void Main(string[] args)
{
    string factString = "中華人民共和國";
    byte[] myByte;
    string Base64Str;

    //先把字串按照utf-8的編碼轉換成byte[]
    Encoding myEncoding = Encoding.GetEncoding("utf-8");

    //myByte中獲得這樣的位元組陣列:228,184,173,229,141,142,228,186,186,230,176,145,229,133,177,229,146,140,229,155,189
    myByte = myEncoding.GetBytes(factString);

    //把byte[]轉成base64編碼,這個例子形成的base64編碼為:"5Lit5Y2O5Lq65rCR5YWx5ZKM5Zu9"
    Base64Str = Convert.ToBase64String(myByte);

    //再從base64編碼轉成byte[],又恢復為位元組陣列:228,184,173,229,141,142,228,186,186,230,176,145,229,133,177,229,146,140,229,155,189
    myByte = Convert.FromBase64String(Base64Str);

    //用同一個Encoding物件把byte[]轉成字串:"中華人民共和國"
    factString = myEncoding.GetString(myByte);

    Console.WriteLine(factString);

}

 (2)

import org.apache.commons.codec.binary.Base64;
public class UtilHelper {    
    //base64字串轉byte[]
    public static byte[] base64String2ByteFun(String base64Str){
        return Base64.decodeBase64(base64Str);
    }
    //byte[]轉base64
    public static String byte2Base64StringFun(byte[] b){
        return Base64.encodeBase64String(b);
    }
}