C # VB implements conversion between 10-to-16 hexadecimal notation

Source: Internet
Author: User
Tags string back

Method 1: Copy codeThe Code is as follows: int d = 10;
D. ToString ("x") // or change x to X, which is a 16-Bit String.
Int x = Convert. ToInt32 (d. ToString ("x"), 16); // Convert the hexadecimal string back to the hexadecimal string.

Method 2: Copy codeThe Code is as follows: static void Main ()
{
Int I = 446;
String hex = I. ToString ("X"/* or x *);
Console. WriteLine (hex );
Int j = HexToInt (hex );
Console. WriteLine (j );
}
Static int HexToInt (string hex)
{
Hex = Regex. Replace (hex, "^ 0x", "", RegexOptions. IgnoreCase );
If (Regex. IsMatch (hex, "[g-z]", RegexOptions. IgnoreCase ))
{
Throw new Exception ("Invalid Hexadecimal Expression.: 0x" + hex );
}
Char [] chars = hex. ToUpper (). ToCharArray ();
Array. Reverse (chars );
Int dec = 0;
For (int I = 0; I <chars. Length; I ++)
{
Dec + = HexMapping (chars [I]) * (int) Math. Pow (16, I );
}
Return dec;
}
Static int HexMapping (char c)
{
Switch (c)
{
Case '0 ':
Return 0;
Case '1 ':
Return 1;
Case '2 ':
Return 2;
Case '3 ':
Return 3;
Case '4 ':
Return 4;
Case '5 ':
Return 5;
Case '6 ':
Return 6;
Case '7 ':
Return 7;
Case '8 ':
Return 8;
Case '9 ':
Return 9;
Case 'A ':
Return 10;
Case 'B ':
Return 11;
Case 'C ':
Return 12;
Case 'D ':
Return 13;
Case 'E ':
Return 14;
Case 'F ':
Return 15;
Default:
Throw new Exception ("Invalid Hexadecimal Character:" + c. ToString ());
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.