Last active
February 3, 2022 22:56
-
-
Save colindooley11/7c19db1f9d42361cd8186b7ea9750ca1 to your computer and use it in GitHub Desktop.
#IPAddress different #octets #bitshifting #bitwiseor #codewars
This file contains 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.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