How-to: 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.

Base 36 has the one disadvantage that it will sometimes randomly produce output which contains a valid word in english, and sometimes that may even be a NSFW 4-letter word, to avoid that issue, you can use Base 31 instead.

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

   Try{
      ForEach ($c in $inputarray) {
         if($alphabet.IndexOf($c) -eq -1){Throw}
         $decNum += $alphabet.IndexOf($c) * [long][Math]::Pow(36, $pos)
         $pos++
      }
      $decNum
   } Catch {
   "Error: invalid character"
   }
}

# 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 PowerShell Cmdlets

Online base 36 converter (Javascript)


 
Copyright © 1999-2025 windevcluster.com
Some rights reserved