views:

485

answers:

2

I have a function that can decode an array of bytes into a string of characters using a specified encoding.

Example:

Function Decode(ByVal bytes() As Byte, ByVal codePage As String) As String
    Dim enc As Text.Encoding = Text.Encoding.GetEncoding(codePage)
    Return enc.GetString(bytes)
End Function

If I want to include base64 in this I have to do something like this:

Function Decode(ByVal bytes() As Byte, ByVal codePage As String) As String
    If String.Compare(codePage, "base64", True) = 0 Then
        Return Convert.ToBase64String(bytes)
    Else
        Dim enc As Text.Encoding = Text.Encoding.GetEncoding(codePage)
        Return enc.GetString(bytes)
    End If
End Function

Why is base64 treated special in .NET?

A: 

It's in System.Convert

Arnshea
Well, the OP uses it in the question, so I'm not sure that is a huge revelation...
Marc Gravell
doh! good point - it's why I voted for Skeet's answer ;)
Arnshea
@Marc : "huge revelation"... LOLzzz!!
Andrei Rinea
+18  A: 

They're really not the same thing:

  • Encodings are ways of representing arbitrary text in binary form.
  • Base64 is a way of representing arbitrary binary data in text form.

You wouldn't normally use them in the same circumstances. You'd use an encoding when the "real" data is text, and base64 when the "real" data is binary.

Of course you could implement an encoding to do base64, but personally I don't think it's a good idea.

Jon Skeet