Determines if given string is in proper hexadecimal string format - CSharp System

CSharp examples for System:Hex

Description

Determines if given string is in proper hexadecimal string format

Demo Code


using System;//from  w  w  w  .j  a  va  2s .  co  m

public class Main{
        /// <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;
        }
}

Related Tutorials