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

$IPaddress=”10.0.0.1″
$subnet=”255.255.255.0″
$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.

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

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 http://www.powershellmagazine.com/2012/10/16/converting-numbers-to-binary-and-back/ and Grumpy Admin doesn’t mind being out smarted sometime! (only some times!!!). So I improve my code by using their code!

$rebuiltip=””
$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!

Hazzy