Alex K Alex K - 1 year ago 216
C# Question

Byte arrays to base64 string

Say I have two byte arrays.

In the first scenario, I concatenate the two arrays (using Buffer.BlockCopy), then convert the result to base64 string.

In the second scenario, I convert each byte array into base64 string and then concatenate those strings.

Would the two results be the same?

Answer Source

Results would be the same if length of the first array is divisible by 3, in all other cases result of concatenation of two base64 strings would be different (and invalid base64) due to padding bytes at the end of first string. Length of second array does not matter for this operation as padding is always at the end.

Why "divisible by 3" - since base64 encodes every 3 bytes into exactly 4 characters arrays of such length will not need padding at the end. See for formal details and for more readable explanation.

I.e. if first array is 4 bytes long you get == at the end of converted string and concatenation with other base64 string will result in invalid base64 text

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

Sample case where concatenation works the same on arrays first or on strings:

 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=
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download