Skip to content

Instantly share code, notes, and snippets.

@s0ren
Last active October 10, 2017 07:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save s0ren/d6930d0ff0e51d70de0e019ae1dd2b55 to your computer and use it in GitHub Desktop.
Save s0ren/d6930d0ff0e51d70de0e019ae1dd2b55 to your computer and use it in GitHub Desktop.
Simple functions to manipulate UInt32 for use with ip addressing.
using System;
namespace ip
{
class MainClass
{
public static void Main(string[] args)
{
//Console.WriteLine("Hello World!");
unchecked
{
ulong ip = (UInt32)(192 << 24) + (168 << 16) + (1 << 8) + 10;
Console.WriteLine(ip);
string ips = (255 & (ip >> 24)) + "."
+ (255 & (ip >> 16)) + "."
+ (255 & (ip >> 8)) + "."
+ (255 & ip);
Console.WriteLine(ips);
}
Console.WriteLine(DDtoUInt("192.168.1.10"));
Console.WriteLine(UIntToDD(DDtoUInt("192.168.1.10")));
Console.WriteLine(CIFStoUint(16));
Console.WriteLine(UIntToDD(CIFStoUint(8)));
Console.WriteLine(UIntToDD(CIFStoUint(16)));
Console.WriteLine(UIntToDD(CIFStoUint(24)));
Console.WriteLine(UIntToBitPattern(DDtoUInt("192.168.1.10")));
Console.WriteLine(UIntToBitPattern(Convert.ToUInt32(-10)));
//Console.WriteLine(UIntToBitPattern(-10));
Console.WriteLine(DDtoUInt("192.168.1.10.22"));
}
public static UInt32 DDtoUInt(string dd)
{
string[] ip_strings = dd.Split('.');
if (ip_strings.Length != 4)
{
throw new FormatException("Forkert format i " + dd);
}
else
{
int[] ip_bytes = {
Convert.ToByte(ip_strings[3]),
Convert.ToByte(ip_strings[2]),
Convert.ToByte(ip_strings[1]),
Convert.ToByte(ip_strings[0])
};
unchecked
{
UInt32 ip = (UInt32)(ip_bytes[3] << 24)
+ (UInt32)(ip_bytes[2] << 16)
+ (UInt32)(ip_bytes[1] << 8)
+ (UInt32)ip_bytes[0];
return ip;
}
}
}
public static string UIntToDD(UInt32 ip)
{
string ips = (255 & (ip >> 24)) + "."
+ (255 & (ip >> 16)) + "."
+ (255 & (ip >> 8)) + "."
+ (255 & ip);
return ips;
}
public static UInt32 CIFStoUint(byte nBits)
{
unchecked
{
UInt32 ip = (UInt32)(~0);
ip = ip << 32 - nBits;
return ip;
}
}
public static string UIntToBitPattern(UInt32 ip)
{
string result = "";
for (int i = 31; i >= 0; i--)
{
result += 1 & (ip >> i);
}
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment