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!
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.
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.
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.
You can use:
From byte[] to string:
byte[] array = somebytearray;
string result = Convert.ToBase64String(array);
From string to byte[]:
array = Convert.FromBase64String(result);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With