More Base… part 2

Previously Grump Admin – wrote about how to convert an IP and Subnet into binary. Using the [System.Convert]::tostring(255,2) method. So we left off with the following code snippet which will present out IP and Subnet in Binary

$ipraw = $ipaddress -split “\.”| ForEach-Object {[System.Convert]::ToString($_,2).PadLeft(8,”0″)}
$subnetraw = $subnet -split “\.”| ForEach-Object {[System.Convert]::ToString($_,2).PadLeft(8,”0″)}
write-host $($ipraw -join ” “)`n$($subnetraw -join ” “)

This is good… but as promised here is how to convert it back. Now we if we follow on and do a $ipraw – you will see the 8 bits as we did the cool padding thing right (actually we did a padleft but meh!) – as we know 8 bits is a byte so all we need to do is to convert the base two into a byte.

$ipraw | foreach-object {$rebuiltip=$rebuiltip +[system.convert]::tobyte($_,2)+”.”}

I think you can tell, I learned to code in BASIC!

But a smarter way – check this blog out as they do exactly what I do 🙂 but in a better way and Grumpy Admin doesn’t mind being out smarted sometime! (only some times!!!). So I improve my code by using their code!

$rebuiltip = $ipraw | foreach-object {[system.convert]::tobyte($_,2)}
$rebuiltip -join “.”

There you have it – Easy code to convert from binary back to base 10! Use their method not mine, it better code… you see it all good learning! Time for my morning coffee!



Leave a Reply

Your email address will not be published. Required fields are marked *