实用代码-C#之IP地址和整数的互转

源码

 1 [StructLayout(LayoutKind.Explicit)]
 2 public struct IP
 3 {
 4     public IP(UInt32 value)
 5     {
 6         this._text1 = 0;
 7         this._text2 = 0;
 8         this._text3 = 0;
 9         this._text4 = 0;
10         this._value = value;
11     }
12     public IP(Byte text1, Byte text2, Byte text3, Byte text4)
13     {
14         this._value = 0;
15         this._text1 = text1;
16         this._text2 = text2;
17         this._text3 = text3;
18         this._text4 = text4;
19     }
20     [FieldOffset(0)]
21     private UInt32 _value;
22     [FieldOffset(0)]
23     private Byte _text1;
24     [FieldOffset(1)]
25     private Byte _text2;
26     [FieldOffset(2)]
27     private Byte _text3;
28     [FieldOffset(3)]
29     private Byte _text4;
30 
31     public UInt32 Value
32     {
33         get { return this._value; }
34         set { this._value = value; }
35     }
36     public Byte Text1
37     {
38         get { return this._text1; }
39         set { this._text1 = value; }
40     }
41     public Byte Text2
42     {
43         get { return this._text2; }
44         set { this._text2 = value; }
45     }
46     public Byte Text3
47     {
48         get { return this._text3; }
49         set { this._text3 = value; }
50     }
51     public Byte Text4
52     {
53         get { return this._text4; }
54         set { this._text4 = value; }
55     }
56 
57     public override string ToString()
58     {
59         return String.Format("{0}.{1}.{2}.{3}", this._text1.ToString(), this._text2.ToString(),
60             this._text3.ToString(), this._text4.ToString());
61     }
62 
63     public static implicit operator IP(UInt32 value)
64     {
65         return new IP(value);
66     }
67     public static explicit operator UInt32(IP ip)
68     {
69         return ip._value;
70     }
71 }

测试

 1 class Program
 2 {
 3     static void Main(string[] args)
 4     {
 5         IP ip = new IP(192,168,1,1);
 6         Console.WriteLine(ip);
 7         UInt32 value = (UInt32)ip;
 8         Console.WriteLine(value);
 9         Console.WriteLine(ip.Value);
10         IP ip2 = (IP)(1234567);
11         Console.WriteLine(ip2);
12         
13         Console.ReadKey();
14     }
15 }

 

posted @ 2013-03-11 14:23  Timetombs  阅读(2111)  评论(6编辑  收藏  举报