Left-Padding a String
I’ll be honest; .NET has more methods and classes and properties than I can shake an idiom at. In my previous blog post, I needed to left-pad a string with zeroes in order to treat it as a 32-bit binary value to [Array]::Reverse()
. I also had to do the same for an 8-bit value, but the method is the same.
Huge, huge gotcha with [Array]::Reverse()
: it returns void
, not the reversed array. It reverses the array in place.
So, I can convert an [int]
to a string representing that value as binary, but if I’m reversing bits, then I need the binary-as-string to be 32 characters long. [Convert]::ToString(8,2)
will return 100
, but I need it to be 00000000000000000000000000000100
so I can reverse it properly. Sure, I can play with $string.Length
and all that, but here's a faster way.
(("0" * 31) + [convert]::ToString($UInt32, 2)) -replace '.*(.{32})$', "`$1"
I know that the resulting string will be 32 characters long, and that the input string will be at least one character. (I know this because I'm already bounds-checking before this. You do bounds-check your input, don't you?) I simply prepend a string of 31 zeroes to my input string, then RegEx out the rest. I don't even need to build out the RegEx as a string because I'm using the count-range-of-previous-(meta)character operator, the {[int] [,[int]]}
specifier. \d{0,10}
means "between 0 and 10 digits" and {[int]}
means only that many of the previous (meta)character.
Edit: Scratch out the part about [Array]::Reverse()
No, it still reverse the array in place and returns void
, but I didn't need it in my current implementation. I needed that static method in a prior one because ([IPAddress]$ipV4Address).Address
was a Big-Endian 32-bit number, and I needed convert it to Little-Endian so I could add an [int]
to it (and then conver it back, etc.) I'm just leaving in the part about [Array]::Reverse()
because I had so much fun with it.
Yeah, let's just leave it at 'fun,' shall we?