簡體   English   中英

字節數組到base64字符串

[英]Byte arrays to base64 string

說我有兩個字節數組。

在第一種情況下,我將兩個數組連接起來(使用Buffer.BlockCopy),然后將結果轉換為base64字符串。

在第二種情況下,我將每個字節數組轉換為base64字符串,然后連接這些字符串。

兩種結果會一樣嗎?

如果第一個數組的長度可被3整除,結果將是相同的,在所有其他情況下,由於第一個字符串末尾的填充字節,兩個base64字符串的連接結果將是不同的(並且無效的base64)。 第二個數組的長度對此操作無關緊要,因為填充始終在末尾。

為什么要“被3整除”-因為base64將每3個字節編碼為恰好4個字符的長度的數組,所以最后不需要填充。 https://tools.ietf.org/html/rfc4648#section-4正式細節和https://en.wikipedia.org/wiki/Base64#Padding為更具可讀性的解釋。

即,如果第一個數組長為4個字節,則在轉換后的字符串的末尾會得到== ,並且與其他base64字符串串聯將導致無效的base64文本

Convert.ToBase64String(new byte[]{1,2,3,4}) // AQIDBA==

串聯在數組或字符串上的工作方式相同的示例情況:

 Convert.ToBase64String(new byte[]{1,2,3}) + // length divisible by 3
 Convert.ToBase64String(new byte[]{4,5}) 
 == 
 Convert.ToBase64String(new byte[]{1,2,3,4,5}) // AQIDBAU=
void Main()
{
    byte[] bytes1 = new byte[]{10, 20, 30, 40, 0, 0, 0, 0};
    byte[] bytes2 = new byte[]{50, 60, 70, 80};

    Buffer.BlockCopy(bytes2, 0, bytes1, 4, 4);

    PrintByteArray(bytes1);

    string bytesStr = Convert.ToBase64String(bytes1);
    Console.WriteLine(bytesStr);

    string bytesStr1 = Convert.ToBase64String(bytes1);
    string bytesStr2 = Convert.ToBase64String(bytes2);

    string bytesStrMerged = bytesStr1 + bytesStr2;
    Console.WriteLine(bytesStrMerged);
}


public void PrintByteArray(byte[] bytes)
{
    var sb = new StringBuilder();
    foreach (var b in bytes)
    {
        sb.Append(b + " ");
    }
    Console.WriteLine(sb.ToString());
}

輸出:

10 20 30 40 50 60 70 80 
ChQeKDI8RlA=
ChQeKDI8RlA=MjxGUA==

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM