I had thought that Convert.ToBase64String() was the method to use to create a base64 string of a byte array, but I recently came across BitConverter.ToString(). What is the difference between the two?
And more specifically when should one be used over the other?
For example in this question about creating a MD5 digest, a comment by CraigS on an answer states “ToBase64String doesn’t return what I want. However, BitConverter.ToString around the byte array does the trick.”
BitConverter.ToString(
MD5.Create().ComputeHash(Encoding.Default.GetBytes(StringToEncode))
).Replace("-", "")
vs
Convert.ToBase64String(
MD5.Create().ComputeHash(Encoding.Default.GetBytes(StringToEncode))
)
Also, what should be used to encode images to base64?
public string ImageToBase64(int Img_ID)
{
byte[] tempBytes = showImageById(Img_ID); // get image from DB
return Convert.ToBase64String(tempBytes);
}
vs
public string ImageToBase64(int Img_ID)
{
byte[] tempBytes = showImageById(Img_ID); // get image from DB
return BitConverter.ToString(tempBytes).Replace("-", "");
}
From MSDN for
Convert.ToBase64String:The wikipedia article on Base64 is much more enlightening about how the algorithm actually works.
The
BitConvertertakes each byte’s hex value as two digits and appends them one after another separated by a dash.Both can be converted both ways.
For readability, the
BitConverterbeats the Base64 string any day, but the Base64 string is more compact.