Share via


One-Liner: Left-Padding a String with Zeroes

Yesterday’s post had a little bit of sleight-of-hand involved.  For the IPv4 address to UInt64 conversion to work, each octet had to be converted into an 8-character string of ones and zeroes.  However, [convert]::ToString($int, 2) doesn’t zero pad, and this is now a string, not an Int, so I can’t use .Net’s ToString() formatting line noise.  This means that the last octet of 192.168.1.0 is a single ‘0’, not an 8 character string.  Instead, this is what I did:

 $bits += (("0" * 7) + [convert]::ToString($_,2)) -replace '.*(.{8})$', "`$1"; 

I prepend 7 zeroes to by the string returned by ToString($_,2).  This means at even a single digit is now 8 characters long. 

That’s great, but what if the octet’s value is 255, which is 8 ‘1’ character?  That would make it 15 characters long, right?

Well, we only need the 8 starting from the right side.  Originally, I tried casting it to [char[]], then taking elements out of the array with negative indexes.  (You did know that $array[-1] returns the last element in the array?  That wasn’t as easy to read as I’d like.

Instead, RegEx to the rescue.  The RegEx pattern, ‘.*(.{8}$’, replaces all but the last 8 characters with nothing (removes them.)  “(.{8}$” specified those last 8 characters from end-of-line (“^”).  Search-and-replace in .NET seems to be designed by someone who hated Perl.  It’s quite painful.  Here, I say this because “`$1” is the way to specify “the matched string in the parenthesis.”  ‘$1’ doesn’t work.  It has to be “`$1”.