Hexa encoder and decoder in c#

namespace HexaEncoding

{

    #region[Directive]

    using System;

    using System.Text;

    #endregion[Directive]

 

    /// <summary>

      /// Summary description for HexEncoding.

      /// </summary>

      public class HexaEncoding

      {

            public HexaEncoding()

            {

                  //

                  // TODO: Add constructor logic here

                  //

            }

            public static int GetByteCount(string hexString)

            {

                  int numHexChars = 0;

                  char c;

                  // remove all none A-F, 0-9, characters

                  for (int i=0; i<hexString.Length; i++)

                  {

                        c = hexString[i];

                        if (IsHexDigit(c))

                              numHexChars++;

                  }

                  // if odd number of characters, discard last character

                  if (numHexChars % 2 != 0)

                  {

                        numHexChars--;

                  }

                  return numHexChars / 2; // 2 characters per byte

            }

            /// <summary>

            /// Creates a byte array from the hexadecimal string. Each two characters are combined

            /// to create one byte. First two hexadecimal characters become first byte in returned array.

            /// Non-hexadecimal characters are ignored.

            /// </summary>

            /// <param name="hexString">string to convert to byte array</param>

            /// <param name="discarded">number of characters in string ignored</param>

            /// <returns>byte array, in the same left-to-right order as the hexString</returns>

            public static byte[] GetBytes(string hexString, out int discarded)

            {

                  discarded = 0;

                  string newString = "";

                  char c;

                  // remove all none A-F, 0-9, characters

                  for (int i=0; i<hexString.Length; i++)

                  {

                        c = hexString[i];

                        if (IsHexDigit(c))

                              newString += c;

                        else

                              discarded++;

                  }

                  // if odd number of characters, discard last character

                  if (newString.Length % 2 != 0)

                  {

                        discarded++;

                        newString = newString.Substring(0, newString.Length-1);

                  }

 

                  int byteLength = newString.Length / 2;

                  byte[] bytes = new byte[byteLength];

                  string hex;

                  int j = 0;

                  for (int i=0; i<bytes.Length; i++)

                  {

                        hex = new String(new Char[] {newString[j], newString[j+1]});

                        bytes[i] = HexToByte(hex);

                        j = j+2;

                  }

                  return bytes;

            }

 

        public static string ToString(byte[] bytes)

        {

            string hexString = "";

            for (int i = 0; i < bytes.Length; i++)

            {

                hexString += bytes[i].ToString("X2");

            }

            return hexString;

        }

 

        public static string ToString(byte[] bytes, int offset, int receiveSize)

        {

            string hexString = "";

            for (int i = offset; i < receiveSize; i++)

            {

                hexString += bytes[i].ToString("X2");

            }

            return hexString;

        }

            /// <summary>

            /// Determines if given string is in proper hexadecimal string format

            /// </summary>

            /// <param name="hexString"></param>

            /// <returns></returns>

            public static bool InHexFormat(string hexString)

            {

                  bool hexFormat = true;

 

                  foreach (char digit in hexString)

                  {

                        if (!IsHexDigit(digit))

                        {

                              hexFormat = false;

                              break;

                        }

                  }

                  return hexFormat;

            }

 

            /// <summary>

            /// Returns true is c is a hexadecimal digit (A-F, a-f, 0-9)

            /// </summary>

            /// <param name="c">Character to test</param>

            /// <returns>true if hex digit, false if not</returns>

            public static bool IsHexDigit(Char c)

            {

                  int numChar;

                  int numA = Convert.ToInt32('A');

                  int num1 = Convert.ToInt32('0');

                  c = Char.ToUpper(c);

                  numChar = Convert.ToInt32(c);

                  if (numChar >= numA && numChar < (numA + 6))

                        return true;

                  if (numChar >= num1 && numChar < (num1 + 10))

                        return true;

                  return false;

            }

            /// <summary>

            /// Converts 1 or 2 character string into equivalant byte value

            /// </summary>

            /// <param name="hex">1 or 2 character string</param>

            /// <returns>byte</returns>

            private static byte HexToByte(string hex)

            {

                  if (hex.Length > 2 || hex.Length <= 0)

                        throw new ArgumentException("hex must be 1 or 2 characters in length");

                  byte newByte = byte.Parse(hex, System.Globalization.NumberStyles.HexNumber);

                  return newByte;

            }

 

            

      }

}

 

 

namespace HexaEncoding

{

    #region[Directive]

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

    #endregion[Directive]

    /// <summary>

    /// This class contain the convertion function

    /// </summary>

    public class DataElementConvertion

    {

        /// <summary>

        /// This function is used to convert hexa value

        /// to char

        /// </summary>

        /// <param name="hexavalue">contain the hexa value</param>

        /// <returns>character representation of the hexa format</returns>

        public static char HexaToChar(string hexavalue)

        {

            StringBuilder hexaString = new StringBuilder();

            hexaString.AppendFormat("0x{0}", hexavalue);

            int hexaNum = Convert.ToInt32(hexaString.ToString(), 16);

            char charValue = Convert.ToChar(hexaNum);

            return charValue;

        }

 

        /// <summary>

        /// This function is used to convert the char to hexa

        /// </summary>

  /// <param name="charvalue">string data type:Contain the char  value</param>

        /// <returns>string data type:Contain the string data</returns>

        public static string ChartoHexa(string charvalue)

        {

            byte[] asciivalue = Encoding.ASCII.GetBytes(charvalue);

            string value = string.Empty;

            for (int i = 0; i < asciivalue.Length; i++)

            {

                value += Convert.ToString(asciivalue[i], 16);

            }

            return value;

        }

 

        /// <summary>

        /// This function is used to convert bit map

        /// to byte

        /// </summary>

        /// <param name="bitmap">string data type</param>

        /// <returns>array of byte</returns>

        public static byte[] bitmapToByte(string bitmap)

        {

             int discard=0;

             return HexaEncoding.GetBytes(bitmap, out discard);

        }

 

        /// <summary>

        /// This function is used to convert the byte to binary

        /// </summary>

        /// <param name="bytes">bytes contain all the bytes</param>

        /// <returns>string data type:return back the string of binary value</returns>

        public static string ByteToBinary(byte[] bytes)

        {

            StringBuilder strbHexa = new StringBuilder();

            foreach (byte data in bytes)

            {

                strbHexa.AppendFormat("{0:x2}", data);

            }

 

            string hexaString = strbHexa.ToString();

 

            string binaryData = string.Empty;

 

            foreach (char hexaChar in hexaString)

            {

                string binaryString = Convert.ToString(Convert.ToInt32(hexaChar.ToString(), 16), 2);

                binaryData += binaryString.Length > 3 ? binaryString : binaryString.PadLeft(4, '0');

            }

 

            return binaryData;

        }

 

        /// <summary>

        /// This function is used to do byte to byte

        /// </summary>

        /// <param name="bytes">bytes contains all the bytes</param>

        /// <returns>string data type:return back the string of binary data</returns>

        public static string ByteToBinary(byte bytes)

        {

            string hexaString = Convert.ToString(bytes, 16);

 

            string binaryData = string.Empty;

 

            foreach (char hexaChar in hexaString)

            {

                string binaryString = Convert.ToString(Convert.ToInt32(hexaChar.ToString(), 16), 2);

                binaryData += binaryString.Length > 3 ? binaryString : binaryString.PadLeft(4, '0');

            }

 

            return binaryData;

        }

 

        /// <summary>

        /// This function is used to do the bit map detail :

        /// ie provide the positions of the data in dataelement string

        /// </summary>

        /// <param name="bytes">array of byte</param>

        /// <returns>array of string</returns>

        public static string[] BitmapDetail(byte[] bytes)

        {

            string binaryData = ByteToBinary(bytes);

            string[] bitMapDetail = new string[binaryData.Length];

            for (int i = 0; i < binaryData.Length; i++)

            {

                bitMapDetail[i] = binaryData[i].ToString() == "1" ? (i + 1).ToString() : string.Empty;

            }

 

            return bitMapDetail;

        }

       

        /// <summary>

        /// This function is used to convert the binary to hexa

        /// </summary>

        /// <param name="binayString">binary string data</param>

        /// <returns>hexa string data</returns>

        public static string BinaryToHexa(string binayString)

        {

            StringBuilder hexaValue = new StringBuilder();

            string[] noOfbytes = BytesDetail(binayString);

            foreach (string bytes in noOfbytes)

            {

                int decimalvalue = BinaryToDecimal(bytes);

                string hexaData = Convert.ToString(decimalvalue, 16);

                hexaValue.Append(hexaData);

            }

            return hexaValue.ToString();

        }

 

        /// <summary>

        /// This function is used to find out no of bytes

        /// </summary>

        /// <param name="binayString">string data type</param>

        /// <returns>array of string data type</returns>

        public static string[] BytesDetail(string binayString)

        {

            string binaryData = binayString;

            Int64 binarylength = binayString.Trim().Length;

            Int64 noBytes = binarylength / 4;

            string[] binaryDetail = new string[noBytes];

            for (int i = 0; i < noBytes; i++)

            {

                int startindex = (4 * i);

                int length = (noBytes == 0) ? 0 :

                    (startindex == 0) ? 4 : (binarylength - startindex) < binarylength ? 4 : 0;

                if (length == 0)

                {

                    binaryDetail[i] = binaryData.Substring(startindex);

                }

                else

                {

                    binaryDetail[i] = binaryData.Substring(startindex, length);

                }

            }

 

            return binaryDetail;

        }

 

        /// <summary>

        /// This function is used to convert binary to decimal

        /// </summary>

        /// <param name="binaryString">binaryString is contain four bits(0000 or 0101) </param>

        /// <returns>return decimal value</returns>

        public static int BinaryToDecimal(string binaryString)

        {

            int decimalValue = 0;

            int j = 0;

            for (int i = binaryString.Length - 1; i >= 0; i--)

            {

                decimalValue += Convert.ToInt32(binaryString[i].ToString()) * Convert.ToInt32(pow(double.Parse("2"), j));

                j++;

            }

            return decimalValue;

        }

 

        /// <summary>

        /// This function is used to calculate the power

        /// of the number

        /// </summary>

        /// <param name="power">double data type</param>

        /// <param name="number">int data type</param>

        /// <returns>double data type</returns>

        public static double pow(double number, int power)

        {

            return power == 0 ? 1 : power == 1 ? number : number * pow(number, --power);

        }

 

        /// <summary>

        /// This function is used to trim the string

        /// </summary>

        /// <param name="isoRequest">string data type</param>

        /// <returns>string data type</returns>

        public static string StringTrim(string isoRequest)

        {

            StringBuilder isoRequestMessage = new StringBuilder();

            char[] isoRequestChar = isoRequest.ToCharArray();

 

            for (int i = 0; i < isoRequestChar.Length; i++)

            {

                if (!string.IsNullOrEmpty(isoRequestChar[i].ToString()))

                {

                    isoRequestMessage.Append(isoRequestChar[i].ToString());

                }

            }

 

            return isoRequestMessage.ToString();

        }

 

        /// <summary>

        /// This function is used to convert the decimal to binary

        /// </summary>

        /// <param name="decimalValue">string Data Type</param>

        /// <returns>string Data Type</returns>

        public static string DecimalToBinary(string decimalValue)

        {

            // Declare a few variables we're going to need

            Int64 BinaryHolder;

            char[] BinaryArray;

            string BinaryResult = "";

            Int64 decivalue = Convert.ToInt64(decimalValue);

            while (decivalue > 0)

            {

                BinaryHolder = decivalue % 2;

                BinaryResult += BinaryHolder;

                decivalue = decivalue / 2;

            }

 

            // The algoritm gives us the binary number in reverse order (mirrored)

            // We store it in an array so that we can reverse it back to normal

            BinaryArray = BinaryResult.ToCharArray();

            Array.Reverse(BinaryArray);

            BinaryResult = new string(BinaryArray);

 

            return BinaryResult.PadLeft(8, '0');

 

 

        }

 

        /// <summary>

        /// This function is used to convert the hexa value to the decimal value

        /// </summary>

        /// <returns>it will return the decimal value as integer</returns>

        public static int HexaToDecimal(string hexaValue)

        {

            int decimalValue = 0;

            int j = 0;

            for (int i = hexaValue.Length - 1; i >= 0; i--)

            {

                int hexaDecivalue = 0;

                switch (hexaValue[i].ToString())

                {

                    case "A": hexaDecivalue = 10; break;

                    case "B": hexaDecivalue = 11; break;

                    case "C": hexaDecivalue = 12; break;

                    case "D": hexaDecivalue = 13; break;

                    case "E": hexaDecivalue = 14; break;

                    case "F": hexaDecivalue = 15; break;

                    default: hexaDecivalue = Convert.ToInt32(hexaValue[i].ToString());

                        break;

 

                }

                decimalValue += hexaDecivalue * Convert.ToInt32(pow(double.Parse("16"), j));

                j++;

            }

            return decimalValue;

        }

 

        /// <summary>

        /// This function will check whether string contain[A-F] or [a-f]

        /// </summary>

        /// <param name="hexaValue">contain the hexa value</param>

        /// <returns>true if hex digit, false if not</returns>

        public static bool IsHexaFormat(string hexaValue)

        {

            bool ishexa = true;

            foreach (char c in hexaValue)

            {

                if (!IsHexaDigit(c))

                {

                    ishexa = false;

                    break;

                }

            }

            return ishexa;

        }

 

        /// <summary>

        /// This function is used to check the char is in hexa format

        /// i.e whether it is contain[A-F]or [a-f]

        /// </summary>

        /// <param name="hexachar">hexa char value</param>

        /// <returns>if hexa true,or false</returns>

        private static bool IsHexaDigit(char c)

        {

            int numChar;

            int numA = Convert.ToInt32('A');

            c = Char.ToUpper(c);

            numChar = Convert.ToInt32(c);

            if (numChar >= numA && numChar < (numA + 6))

                return true;

           return false;

        }

 

        /// <summary>

        /// This function is used to convert the decimal value to

        /// the hexa

        /// </summary>

        /// <param name="value">decimal value</param>

        /// <returns>return hexa value</returns>

        public static string DecimalToHexa(int value)

        {

            Int64 HexaHolder;

            char[] HexaArray;

            string HexaResult = "";

            Int64 decivalue = value;

            while (decivalue > 0)

            {

                HexaHolder = decivalue % 16;

                string hexavalue = string.Empty;

                switch (HexaHolder.ToString())

                {

                    case "10":

                        hexavalue = "A";

                        break;

                    case "11":

                        hexavalue = "B";

                        break;

                    case "12":

                        hexavalue = "C";

                        break;

                    case "13":

                        hexavalue = "D";

                        break;

                    case "14":

                        hexavalue = "E";

                        break;

                    case "15":

                        hexavalue = "F";

                        break;

                    default:

                        hexavalue = HexaHolder.ToString();

                        break;

                }

 

                HexaResult += hexavalue;

                decivalue = decivalue / 16;

            }

 

            // The algoritm gives us the binary number in reverse order (mirrored)

            // We store it in an array so that we can reverse it back to normal

            HexaArray = HexaResult.ToCharArray();

            Array.Reverse(HexaArray);

            HexaResult = new string(HexaArray);

            return HexaResult;

        }

    }

}