Subscribe

RSS Feed (xml)

Encode Binary Data as Text in Csharp

Base64 is an encoding scheme that enables you to represent binary data as a series of ASCII characters so that it can be included in text files and e-mail messages in which raw binary data is unacceptable. Base64 encoding works by spreading the contents of 3 bytes of input data across 4 bytes and ensuring each byte uses only the 7 low-order bits to contain data. This means that each byte of Base64-encoded data is equivalent to an ASCII character and can be stored or transmitted anywhere ASCII characters are permitted. The ToBase64String and FromBase64String methods of the Convert class make it straightforward to Base64 encode and decode data. However, before Base64 encoding, you must convert your data to a byte array. Likewise, after decoding you must convert the byte array back to the appropriate data type;
The code shown here demonstrates how to Base64 encode and decode a Unicode string, an int, and a decimal using the Convert class. The DecimalToBase64 and Base64ToDecimal methods rely on the ByteArrayToDecimal and DecimalToByteArray methods listed . // Base64 encode a Unicode string public static string StringToBase64 (string src) { // Get a byte representation of the source string byte[] b = Encoding.Unicode.GetBytes(src); // Return the Base64-encoded string return Convert.ToBase64String(b); } // Decode a Base64-encoded Unicode string public static string Base64ToString (string src) { // Decode the Base64-encoded string to a byte array byte[] b = Convert.FromBase64String(src); // Return the decoded Unicode string return Encoding.Unicode.GetString(b); } // Base64 encode a decimal public static string DecimalToBase64 (decimal src) { // Get a byte representation of the decimal byte[] b = DecimalToByteArray(src); // Return the Base64-encoded decimal return Convert.ToBase64String(b); } // Decode a Base64-encoded decimal public static decimal Base64ToDecimal (string src) { // Decode the Base64-encoded decimal to a byte array byte[] b = Convert.FromBase64String(src); // Return the decoded decimal return ByteArrayToDecimal(b); } // Base64 encode an int public static string IntToBase64 (int src) { // Get a byte representation of the int byte[] b = BitConverter.GetBytes(src); // Return the Base64-encoded int return Convert.ToBase64String(b); } // Decode a Base64-encoded int public static int Base64ToInt (string src) { // Decode the Base64-encoded int to a byte array byte[] b = Convert.FromBase64String(src); // Return the decoded int return BitConverter.ToInt32(b,0); }

No comments:

Post a Comment

Archives

LocalsAdda.com-Variety In Web World

Fun Mail - Fun in the Mail