Skip to content

Instantly share code, notes, and snippets.

@colindooley11
Last active February 3, 2022 22:56
Show Gist options
  • Save colindooley11/7c19db1f9d42361cd8186b7ea9750ca1 to your computer and use it in GitHub Desktop.
Save colindooley11/7c19db1f9d42361cd8186b7ea9750ca1 to your computer and use it in GitHub Desktop.
#IPAddress different #octets #bitshifting #bitwiseor #codewars
using System;
using System.Linq;
public class CountIPAddresses
{
public static long IpsBetween(string s, string e)
{
var start = s.Split('.').Select(x=> Convert.ToInt32(x)).ToArray();
var end = e.Split('.').Select(x=> Convert.ToInt32(x)).ToArray();
var startAcc = start[0] << 24 | start[1] << 16 | start[2] << 8 | start[3];
var endAcc = end[0] << 24 | end[1] << 16 | end[2] << 8 | end[3];
return endAcc - startAcc;
}
}
// been a loong time since I used bitwise operators.....
Best solution spotted for me:
public static long IpsBetween(string start, string end)
{
return (long)(uint)IPAddress.NetworkToHostOrder((int)IPAddress.Parse(end).Address) -
(long)(uint)IPAddress.NetworkToHostOrder((int)IPAddress.Parse(start).Address);
}
LINQ special
public static long IpsBetween(string start, string end)
{
Func<string, int> fn = str => str.Split('.').Reverse().Select((s, i) => int.Parse(s) << i * 8).Aggregate(0, (current, result) => current + result);
return fn(end) - fn(start);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment