PowerShell Script to Convert Decimal to Binary Number
[Convert]::ToString(decimalNumber, 2) to convert a decimal number to its binary string representation.Examples
How to Think About It
Algorithm
Code
param([int]$decimalNumber) $binaryString = [Convert]::ToString($decimalNumber, 2) Write-Output $binaryString
Dry Run
Let's trace converting decimal 10 to binary using the script.
Input decimal number
decimalNumber = 10
Convert decimal to binary string
[Convert]::ToString(10, 2) returns '1010'
Output binary string
Print '1010'
| Decimal | Binary String |
|---|---|
| 10 | 1010 |
Why This Works
Step 1: Using built-in conversion
PowerShell's [Convert] class has a method ToString that converts numbers to strings in any base, here base 2 for binary.
Step 2: Passing base 2
Passing 2 as the second argument tells the method to convert the decimal number into binary format.
Step 3: Output as string
The method returns the binary number as a string, which can be printed or used further.
Alternative Approaches
param([int]$decimalNumber) $binary = '' if ($decimalNumber -eq 0) { $binary = '0' } while ($decimalNumber -gt 0) { $remainder = $decimalNumber % 2 $binary = $remainder.ToString() + $binary $decimalNumber = [math]::Floor($decimalNumber / 2) } Write-Output $binary
param([int]$decimalNumber) $binaryString = $decimalNumber.ToString(2) Write-Output $binaryString
Complexity: O(log n) time, O(log n) space
Time Complexity
Conversion depends on the number of bits in the decimal number, which is proportional to log base 2 of the number.
Space Complexity
The binary string length grows with the number of bits, so space is proportional to log base 2 of the input number.
Which Approach is Fastest?
Using the built-in [Convert]::ToString method is fastest and simplest compared to manual division.
| Approach | Time | Space | Best For |
|---|---|---|---|
| [Convert]::ToString | O(log n) | O(log n) | Quick and reliable conversion |
| Manual division | O(log n) | O(log n) | Learning and understanding conversion process |
| .ToString(2) method | O(log n) | O(log n) | Modern PowerShell versions, concise code |