Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to base64 byte array, would this be valid?

I'm trying to write a function that converts a string to a base64 byte array. I've tried with this approach:

public byte[] stringToBase64ByteArray(String input) {     byte[] ret = System.Text.Encoding.Unicode.GetBytes(input);     string s = Convert.ToBase64String(input);     ret = System.Text.Encoding.Unicode.GetBytes(s);     return ret; } 

Would this function produce a valid result (provided that the string is in unicode)? Thanks!

like image 977
Tomas Vinter Avatar asked Feb 19 '10 10:02

Tomas Vinter


People also ask

How do you convert a string to Base64?

To convert a string into a Base64 character the following steps should be followed: Get the ASCII value of each character in the string. Compute the 8-bit binary equivalent of the ASCII values. Convert the 8-bit characters chunk into chunks of 6 bits by re-grouping the digits.

How do you convert bytes to Base64 strings?

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. Finally the Byte Array is saved to Folder on Disk as File using WriteAllBytes method of the File class.

Can we convert string to byte?

A String is stored as an array of Unicode characters in Java. To convert it to a byte array, we translate the sequence of characters into a sequence of bytes. For this translation, we use an instance of Charset. This class specifies a mapping between a sequence of chars and a sequence of bytes.


2 Answers

You can use:

From byte[] to string:

byte[] array = somebytearray;

string result = Convert.ToBase64String(array);

From string to byte[]:

array = Convert.FromBase64String(result);

like image 169
Sonhja Avatar answered Oct 14 '22 20:10

Sonhja


Looks okay, although the approach is strange. But use Encoding.ASCII.GetBytes() to convert the base64 string to byte[]. Base64 encoding only contains ASCII characters. Using Unicode gets you an extra 0 byte for each character.

like image 39
Hans Passant Avatar answered Oct 14 '22 20:10

Hans Passant