Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An efficient way to Base64 encode a byte array?

Tags:

c#

.net

I have a byte[] and I'm looking for the most efficient way to base64 encode it.

The problem is that the built in .Net method Convert.FromBase64CharArray requires a char[] as an input, and converting my byte[] to a char[] just to convert it again to a base64 encoded array seems pretty stupid.

Is there any more direct way to do it?

[[EDIT:]] I'll expaling what I want to acheive better - I have a byte[] and I need to return a new base64 encoded byte[]

like image 777
sternr Avatar asked Aug 29 '12 12:08

sternr


People also ask

How efficient is Base64 encoding?

Although Base64 is a relatively efficient way of encoding binary data it will, on average still increase the file size for more than 25%. This not only increases your bandwidth bill, but also increases the download time.

Is Base64 a byte array?

The Byte Array is then converted into Base64 encoded string using the Convert. ToBase64String method. Now in order to save the Base64 encoded string as Image File, the Base64 encoded string is converted back to Byte Array using the Convert. FromBase64String function.

Is Base64 more efficient than hex?

The difference between Base64 and hex is really just how bytes are represented. Hex is another way of saying "Base16". Hex will take two characters for each byte - Base64 takes 4 characters for every 3 bytes, so it's more efficient than hex.

Is Base64 and bytes same?

Each Base64 digit represents exactly 6 bits of data. So, three 8-bits bytes of the input string/binary file (3×8 bits = 24 bits) can be represented by four 6-bit Base64 digits (4×6 = 24 bits).


2 Answers

Byte[] -> String: use system.convert.tobase64string

Convert.ToBase64String(byte[] data)

String -> Byte[]: use system.convert.frombase64string

Convert.FromBase64String(string data)
like image 194
Stephan Schinkel Avatar answered Oct 12 '22 15:10

Stephan Schinkel


Base64 is a way to represent bytes in a textual form (as a string). So there is no such thing as a Base64 encoded byte[]. You'd have a base64 encoded string, which you could decode back to a byte[].

However, if you want to end up with a byte array, you could take the base64 encoded string and convert it to a byte array, like:

string base64String = Convert.ToBase64String(bytes);
byte[] stringBytes = Encoding.ASCII.GetBytes(base64String);

This, however, makes no sense because the best way to represent a byte[] as a byte[], is the byte[] itself :)

like image 29
Eren Ersönmez Avatar answered Oct 12 '22 13:10

Eren Ersönmez