共用方式為


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?

Comments

  • Anonymous
    February 17, 2015
    How about just using: $UInt32 = 100 $UInt32.ToString("D32")

  • Anonymous
    February 17, 2015
    The comment has been removed

  • Anonymous
    February 17, 2015
    I just realized, my recommendation does not address your requirement for representing the number as binary.  My answer formats the number as decimal, base 10 number padded to 32 characters.  Back to the drawing board.

  • Anonymous
    February 18, 2015
    Leave it in a bit-based state and rely on bit-based operations?

  • Anonymous
    February 18, 2015
    The comment has been removed