C # example of IP address and Integer Conversion

Source: Internet
Author: User

Source code:

Copy codeThe Code is as follows: [StructLayout (LayoutKind. Explicit)]
Public struct IP
{
Public IP (UInt32 value)
{
This. _ text1 = 0;
This. _ text2 = 0;
This. _ text3 = 0;
This. _ text4 = 0;
This. _ value = value;
}
Public IP (Byte text1, Byte text2, Byte text3, Byte text4)
{
This. _ value = 0;
This. _ text1 = text1;
This. _ text2 = text2;
This. _ text3 = text3;
This. _ text4 = text4;
}
[FieldOffset (0)]
Private UInt32 _ value;
[FieldOffset (0)]
Private Byte _ text1;
[FieldOffset (1)]
Private Byte _ text2;
[FieldOffset (2)]
Private Byte _ text3;
[FieldOffset (3)]
Private Byte _ text4;

Public UInt32 Value
{
Get {return this. _ value ;}
Set {this. _ value = value ;}
}
Public Byte Text1
{
Get {return this. _ text1 ;}
Set {this. _ text1 = value ;}
}
Public Byte Text2
{
Get {return this. _ text2 ;}
Set {this. _ text2 = value ;}
}
Public Byte Text3
{
Get {return this. _ text3 ;}
Set {this. _ text3 = value ;}
}
Public Byte Text4
{
Get {return this. _ text4 ;}
Set {this. _ text4 = value ;}
}

Public override string ToString ()
{
Return String. Format ("{0}. {1}. {2}. {3}", this. _ text1.ToString (), this. _ text2.ToString (),
This. _ text3.ToString (), this. _ text4.ToString ());
}

Public static implicit operator IP (UInt32 value)
{
Return new IP (value );
}
Public static explicit operator UInt32 (IP)
{
Return ip. _ value;
}
}

Test:

Copy codeThe Code is as follows: class Program
{
Static void Main (string [] args)
{
IP address = new ip (192,168 );
Console. WriteLine (ip );
UInt32 value = (UInt32) ip address;
Console. WriteLine (value );
Console. WriteLine (ip. Value );
IP ip2 = (IP) (1234567 );
Console. WriteLine (ip2 );

Console. ReadKey ();
}
}

Related Article

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.