Skip to content

Instantly share code, notes, and snippets.

@splatteredbits
Last active January 20, 2023 03:47
Show Gist options
  • Save splatteredbits/0557ece45f2dbb8f5cc48573efedf46f to your computer and use it in GitHub Desktop.
Save splatteredbits/0557ece45f2dbb8f5cc48573efedf46f to your computer and use it in GitHub Desktop.
Converts a number into a string using an arbitrary radix/base from 2 to 80. Uses all characters allowed by Windows, macOS, and Linux.
function Convert-Radix
{
<#
.SYNOPSIS
Converts a number to a string using an arbitrary radix/base.
.DESCRIPTION
The `Convert-Radix` function converts a number to a string, using an arbitrary radix/base. The resulting string can
be used as a filename. The function uses letters a-z then characters "!#$%&''()+,-;=@^_`{}~", for numbers
above 9 and below 60. It doesn't use upper case letters (because Windows is case-insensitive) and characters that
are not suitable for Windows, Linux, and macOS file systems. Also omits the letter `n` because Windows doesn't like
file names `nul` and `con` and `n` was a common letter between the two.
Pass the number you want to convert to the `InputObject` parameter, or pipe numbers to the function. For each
number, you'll get a string back of that number converted to the chosen radix. By default, the function uses a radix
of 35 so that the returned string will only have letters and numbers.
Adapted from https://stackoverflow.com/questions/34574203/c-sharp-base-converter.
.EXAMPLE
15 | ConvertTo-Radix -Radix 16
In this example, a number is converted to base-16 string `f`.
.EXAMPLE
34 | ConvertTo-Radix
Demonstrates that the default radix is 35. Returns `z`, the 35th letter in the set 0-9, a-z (except the letter `n`).
#>
[CmdletBinding()]
param(
[Parameter(Mandatory, ValueFromPipeline)]
[UInt64] $InputObject,
[ValidateRange(2,60)]
[UInt16] $Radix = 35
)
begin
{
Set-StrictMode -Version 'Latest'
[char[]] $alphabet =
'0123456789abcdefghijklmopqrstuvwxyz!#$%&''()+,-;=@^_`{}~'.ToCharArray()
}
process
{
if ($InputObject -lt $Radix)
{
return $alphabet[$InputObject].ToString()
}
$result = [Text.StringBuilder]::New()
[UInt64] $index = 0
while ($InputObject -ne 0)
{
$index = $InputObject % $Radix
$InputObject = [Convert]::ToUInt64([Math]::Floor($InputObject / $Radix))
[void] $result.Insert(0, $alphabet[$index])
}
return $result.ToString()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment