Converting strings to numeric values

In most cases, strings may be cast back to numeric values. For example:

[Int]"2"             # String to Int32 
[Decimal]"3.141"     # String to Decimal 
[UInt32]10           # Int32 to UInt32 
[SByte]-5            # Int32 to SByte 

For advanced conversions, the System.Convert class may be used. When exploring Base64 encoding, the Convert.To<NumericType> method was used. This method can take a string and convert it to a number using a specified base.

A binary, base 2, value is converted as follows:

[Convert]::ToInt32('01000111110101', 2)  # Returns 4597 

Or a hexadecimal value, base 16:

[Convert]::ToInt32('FF9241', 16)  # Returns 16749121 

Supported bases are 2 (binary), 8 (octal), 10 (denary), and 16 (hexadecimal).

Get Mastering Windows PowerShell Scripting - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.