using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ArrayToHex
{
    public static class StringExtensions
    {
        // Convert a string into an array of bytes holding the string's Unicode.
        public static byte[] UnicodeBytes(this string text)
        {
            UnicodeEncoding encoder = new UnicodeEncoding();
            return encoder.GetBytes(text);
        }

        // Convert an array holding Unicode bytes into a string.
        public static string ToUnicodeString(this byte[] bytes)
        {
            UnicodeEncoding encoder = new UnicodeEncoding();
            return encoder.GetString(bytes);
        }

        // Return a string that represents the byte array as a series
        // of hexadecimal values separated by a separator character.
        public static string ToHex(this byte[] bytes, char separator)
        {
            return BitConverter.ToString(bytes, 0).Replace('-', separator);
        }

        // Convert a string containing 2-digit hexadecimal values into a byte array.
        public static byte[] ToBytes(this string text)
        {
            // Get the separator character.
            char separator = text[2];

            // Split at the separators.
            string[] pairs = text.Split(separator);
            byte[] bytes = new byte[pairs.Length];
            for (int i = 0; i < pairs.Length; i++)
                bytes[i] = Convert.ToByte(pairs[i], 16);
            return bytes;
        }
    }
}
