Created
July 10, 2025 16:37
-
-
Save Bill-Stewart/76e13c2df56689354375a562c3f082c3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ConvertTo-BinaryString.ps1 | |
# Written by Bill Stewart (bstewart AT iname.com) | |
# I wrote this for two main reasons... | |
# * "b" format specifier not universally available | |
# * [Convert]::ToString() doesn't support UInt64 values | |
<# | |
.SYNOPSIS | |
Converts an unsigned integer to a binary string. | |
.DESCRIPTION | |
Converts an unsigned integer to a binary string. | |
.PARAMETER Value | |
Specifies the unsigned integer value. | |
.PARAMETER Width | |
Specifies the minimum width of the output string. This parmameter must be in the range 1 through 64. | |
.PARAMETER LeadingZeros | |
Specifies that the binary string should include leading zeros. | |
#> | |
param( | |
[Parameter(Position = 0,Mandatory,ValueFromPipeline)] | |
[UInt64] | |
$Value, | |
[Parameter(Position = 1)] | |
[ValidateRange(1,64)] | |
[Int] | |
$Width = 1, | |
[Switch] | |
$LeadingZeros | |
) | |
# Zero is zero... | |
if ( $Value -eq 0 ) { | |
('0',('0' * $Width))[$LeadingZeros.IsPresent] | |
return | |
} | |
# Outputs the number of bits in the specified value | |
function Get-BitWidth { | |
[CmdletBinding()] | |
param( | |
[Parameter(Position = 0,Mandatory)] | |
[UInt64] | |
$value | |
) | |
$width = 1 | |
while ( $value -gt 0 ) { | |
$value = $value -shr 1 | |
if ( $value -gt 0 ) { $width++ } | |
} | |
$width | |
} | |
# Get number of bits in the value | |
$valueWidth = Get-BitWidth $Value | |
# Widen if specified width too small | |
$Width = ($Width,$valueWidth)[$valueWidth -gt $Width] | |
# Populate character array with set bits | |
$chars = New-Object Char[] $Width | |
for ( $i = $Width - 1; $i -ge 0; $i-- ) { | |
$chars[$i] = ('0','1')[$Value -band 1] | |
$Value = $Value -shr 1 | |
} | |
if ( $LeadingZeros ) { | |
$chars -join '' | |
} | |
else { | |
$chars[$chars.IndexOf([Char] '1')..$chars.GetUpperBound(0)] -join '' | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment