There are two ways of doing this:
1. To convert to a signed integer, use Convert.ToInt32 (string, 16);
To convert to an unsigned integer, use Convert.touint32 (String, 16).
If the 16 binary string does not start with 0x or 0X, such as "af37", it can also be converted using this method.
2. To convert to a signed integer, use new System.ComponentModel.Int32Converter (). ConvertFromString (string);
To convert to an unsigned integer, use new System.ComponentModel.UInt32Converter (). ConvertFromString (String).
Attention:
This method is used to force type conversions.
If the 16 binary string does not start with 0x or 0X, this method cannot be used.
Both of these methods are insensitive to the case of letters, and the strings start with 0 x or 0x. For characters that may appear in a 16 binary representation (from a to f), either uppercase or lowercase, or even a mixed-case representation, such as a string such as 0XA3BF2, can be handled correctly.
Regardless of which method you use, do not forget to handle the exceptions that might be thrown.
A sample code is given below:
/************************************************** * Author:han Wei * Author ' s blog:http://blog.csdn.net/henter/* Date:april 22nd * Description:demonstrate How to convert hexadecimal string* with leading 0x into int Eger**************************************************/using System;namespace HexStringConvertToInt{Class Program {static void Main (string[] args) {string hexvalue = "0XA3BF2B10"; Method 1:console.writeline ("Method 1:"); int decvalue = 0; try {decvalue = Convert.ToInt32 (Hexvalue, 16); } catch (Exception e) {Console.WriteLine ("An error occurred while converting!"); Console.WriteLine ("Error message:" + e.message); Console.ReadLine (); Return } Console.WriteLine ("Signed integer value: {0}", Decvalue); UINT UDEcvalue = 0; try {udecvalue = Convert.touint32 (Hexvalue, 16); } catch (Exception e) {Console.WriteLine ("An error occurred while converting!"); Console.WriteLine ("Error message:" + e.message); Console.ReadLine (); Return } Console.WriteLine ("Unsigned integer value: {0}", Udecvalue); Console.WriteLine (); Method 2:console.writeline ("------------------------------"); Console.WriteLine ("Method 2:"); int ivalue = 0; try {ivalue = (int) new System.ComponentModel.Int32Converter (). ConvertFromString (Hexvalue); } catch (Exception e) {Console.WriteLine ("An error occurred while converting!"); Console.WriteLine ("Error message:" + e.message); Console.ReadLine (); Return } Console.WriteLine ("Signed integer value: {0}", ivalue); UINT Uvalue = 0; try {Uvalue = (UINT) new System.ComponentModel.UInt32Converter (). ConvertFromString (Hexvalue); } catch (Exception e) {Console.WriteLine ("An error occurred while converting!"); Console.WriteLine ("Error message:" + e.message); Console.ReadLine (); Return } Console.WriteLine ("Unsigned integer value: {0}", Uvalue); Console.ReadLine (); } }}
C # converts 16 binary strings starting with 0x to corresponding integers