Created
December 13, 2017 14:58
-
-
Save s0ren/2b185f700a9dbb3fd206aecb243a8e21 to your computer and use it in GitHub Desktop.
"union" like struct in C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using System.Runtime.InteropServices; | |
namespace ConsoleApp1 | |
{ | |
[StructLayout(LayoutKind.Explicit)] | |
public struct IP_ADDR | |
{ | |
[FieldOffset(3)] | |
public byte b1; | |
[FieldOffset(2)] | |
public byte b2; | |
[FieldOffset(1)] | |
public byte b3; | |
[FieldOffset(0)] | |
public byte b4; | |
[FieldOffset(0)] | |
public UInt32 addr; | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
IP_ADDR localhost = new IP_ADDR(); | |
localhost.b1 = 127; | |
localhost.b2 = 0; | |
localhost.b3 = 0; | |
localhost.b4 = 1; | |
Console.WriteLine(localhost); | |
Console.WriteLine(localhost.addr); | |
Console.WriteLine( Convert.ToString(localhost.addr, 2) ); | |
Console.WriteLine("{0}.{1}.{2}.{3}", | |
localhost.b1, localhost.b2, localhost.b3, localhost.b4); | |
Console.WriteLine("{0}.{1}.{2}.{3}", | |
Convert.ToString(localhost.b1, 2), | |
Convert.ToString(localhost.b2, 2), | |
Convert.ToString(localhost.b3, 2), | |
Convert.ToString(localhost.b4, 2) | |
); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment