Try to parse string in hexidecimal format to byte in CSharp

Description

The following code shows how to try to parse string in hexidecimal format to byte.

Example


using System;/*from  w  ww  .  j a  v  a 2  s.  co m*/
using System.Globalization;

public class MainClass
{
   public static void Main()
   {
      string byteString; 
      NumberStyles styles;


      byteString = "FF";
      styles = NumberStyles.HexNumber;
      CallTryParse(byteString, styles);

      byteString = "0x1F";
      CallTryParse(byteString, styles);
   }

   private static void CallTryParse(string stringToConvert, NumberStyles styles)
   {  
      Byte byteValue;
      bool result = Byte.TryParse(stringToConvert, styles, 
                                  null as IFormatProvider, out byteValue);
      if (result){
         Console.WriteLine("Converted '{0}' to {1}",stringToConvert, byteValue);
      }else{
         Console.WriteLine("Attempted conversion of '{0}' failed.", stringToConvert.ToString());
      }
   }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Data Types »




C# Data Types
Bool
Byte
Char
Decimal
Double
Float
Integer
Long
Short
String
C# Array
Array Example
Byte Array
C# Standard Data Type Format
BigInteger
Complex
Currency
DateTime
DateTimeOffset
DateTime Format Parse Convert
TimeSpan
TimeZone
Enum
Null
tuple
var