前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >实用代码-C#之IP地址和整数的互转

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

作者头像
blackheart
发布2018-01-19 16:14:06
1.4K0
发布2018-01-19 16:14:06
举报

源码

 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 }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2013-03-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 源码
  • 测试
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档