PowerShell Base 36 functions

Base 36 is the most compact case-insensitive alphanumeric numbering system. Base 36 is used for Dell Express Service Codes, website url shorteners and many other applications which have a need to minimise human error.

Convert from Decimal (base 10) to Base 36:

function convertTo-Base36 {
[CmdletBinding()]
param ([parameter(valuefrompipeline=$true, HelpMessage="Integer number to convert")][int]$decNum="")
$alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"

do {
  $remainder = ($decNum % 36)
  $char = $alphabet.substring($remainder,1)
  $base36Num = "$char$base36Num"
  $decNum = ($decNum - $remainder) / 36
 }
while ($decNum -gt 0)

$base36Num
}

# source: adapted from Tony Marston's PHP code

Convert from Base 36 back to Decimal:

function convertFrom-base36 {
[CmdletBinding()]
param ([parameter(valuefrompipeline=$true, HelpMessage="Alphadecimal string to convert")][string]$base36Num="")
$alphabet = "0123456789abcdefghijklmnopqrstuvwxyz"
$inputarray = $base36Num.tolower().tochararray()
[array]::reverse($inputarray)
[long]$decNum=0
$pos=0

foreach ($c in $inputarray) {
   $decNum += $alphabet.IndexOf($c) * [long][Math]::Pow(36, $pos)
   $pos++
}
$decNum
}

# source: Mirko's Blog

Examples

PS C:\> convertTo-Base36 1645205
Z9G5

PS C:\> convertFrom-base36 z9g5
1645205

“Failure is not fatal, but failure to change might be” - John Wooden

Related:

Online base 36 converter (Javascript)


© Copyright SS64.com 1999-2014
Some rights reserved