String Byte Conversion in C#

string-byte-conversion-in-c

Many a times an API call requires Byte array as argument when we have string to pass and it requires a conversion to be carried out. We can use static method GetBytes available in UTF8Encoding.UTF8 to get the array of bytes out of String we passed. Apart from UTF8Encoding you can also use UTF7Encoding and UTF32Encoding See following statements for an example :

1
2
3
UTF32Encoding.UTF32.GetBytes(inputString);
UTF7Encoding.UTF7.GetBytes(inputString);
UTF8Encoding.UTF8.GetBytes(inputString);

Similarly we get byte array as output from method calls and we need to convert them to String for any useful stuff and we again use same class to get String out of Byte array. See examples below :

1
2
3
UTF32Encoding.UTF32.GetString(inputByteArray);
UTF7Encoding.UTF7.GetString(inputByteArray);
UTF8Encoding.UTF8.GetString(inputByteArray);

My problem was that I tend to forget the conversion each time I required and had to make a google search in order to get a conversion. So I added them in my library and used my APIs to make a conversion.

These conversion methods can be found in StringHelper class under TPLibrary namesapce. For your reference you can have the code below for the conversion I created :

1
2
3
4
5
6
7
8
public static Byte[] StringToByte(String input)
{
    return UTF8Encoding.UTF8.GetBytes(input);
}
public static String ByteToString(Byte[] input)
{
    return UTF8Encoding.UTF8.GetString(input);
}

Use following statements to use them :

1
2
String output = StringHelper.ByteToString(inputArray);
Byte[] output = StringHelper.StringToByte(inputString);

Get latest TPLibrary.dll for your use from TechPhernalia Download page.

One thought on “String Byte Conversion in C#

Leave a Reply