Friday, November 3, 2017

Utility C# Class to Convert String and Bytes

Many times I have found myself  needing to convert bytes to strings or vice-versa. This is actually pretty easy to do in C# however is very easy to forget.  Most examples usually include default encoding to their liking. I have found many times I need a different encoding and sometimes different encoding in the same project. 

Easily solved by the following example.


using System;
using System.Text;
namespace BytesToStrings
{
class Program
{
static void Main(string[] args)
{
string convertMe = "abcdefghijKLMNOPQRSTUVXYZ12345!@#$%^&*(";
Console.Write("Buffer converted default encoding ... ");
byte[] testBuffer = convertMe.ConvertToBytes();
foreach (var b in testBuffer)
Console.Write($"{b} ");
Console.WriteLine();
Console.Write("Back to string ..");
Console.WriteLine(testBuffer.ConvertToString());
Console.Write("Buffer converted default utf_8 ... ");
testBuffer = convertMe.ConvertToBytes(MyByteStringConverter.EncodingType.utf_8);
foreach (var b in testBuffer)
Console.Write($"{b} ");
Console.WriteLine();
Console.Write("Back to string ..");
Console.WriteLine(testBuffer.ConvertToString(MyByteStringConverter.EncodingType.utf_8));
Console.Read();
}
}
public static class MyByteStringConverter
{
// Default Encoding Remove or add as needed
public enum EncodingType
{
utf_16,
utf_16BE,
utf_32,
utf_32BE,
us_ascii,
iso_8859_1,
utf_7,
utf_8
}
// Default encoding change as needed.
private const EncodingType defaultEncodingType = EncodingType.us_ascii;
// Converts Enumeration to Useable Encoding Name as "-" are illegal
private static Encoding EncodingTypeToEncoding(EncodingType encodingInfo)
{
return Encoding.GetEncoding(Enum.GetName(typeof(EncodingType), encodingInfo).Replace("_", "-"));
}
// Byte[] -> String
public static string BytesToString(byte[] bytes, EncodingType encodingInfo = defaultEncodingType)
{
return EncodingTypeToEncoding(encodingInfo).GetString(bytes);
}
// String -> Byte[]
public static byte[] StringToBytes(string str, EncodingType encodingInfo = defaultEncodingType)
{
return EncodingTypeToEncoding(encodingInfo).GetBytes(str);
}
// Byte[] -> String extension method
public static byte[] ConvertToBytes(this string str, EncodingType encodingInfo = defaultEncodingType)
{
return StringToBytes(str);
}
// String -> Byte[] extension method
public static string ConvertToString(this byte[] str, EncodingType encodingInfo = defaultEncodingType)
{
return BytesToString(str);
}
}
}

The main feature of this is that a enumeration was created with the common encoding then a static variable is used to store my preferred default. If an alternative encoding is needed I just provide a optional EncodingType parameter to my preferred conversion.

Pretty useful :)

Utility C# Class to Convert String and Bytes

Many times I have found myself  needing to convert bytes to strings or vice-versa. This is actually pretty easy to do in C# however is very ...