How-to: PowerShell Base 31 functions

Base 36 is the most compact case-insensitive alphanumeric numbering system. Base 36 does have one disadvantage in 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.

Base 31, removes vowels (A,E,I,O,U) from the output and so avoids this issue at the cost of making the output slightly less compact. There are a few English words that don't contain a vowel: Crypt, Fly, Gym but nothing problematic.

Removing vowels also minimises any possible dictation/human errors between 1 and i or between 0 and O. The output is always in capitals so confusion between L and 1 is unlikely.

Convert from Decimal (base 10) to Base 31:

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

   $alphabet = "0123456789BCDFGHJKLMNPQRSTVWXYZ"

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

   $base31Num
}

# source: adapted from Tony Marston’s PHP code

Convert from Base 31 back to Decimal:

function convertFrom-base31 {
   [CmdletBinding()]
   param (
      [parameter(
      valuefrompipeline = $true,
      HelpMessage = "Alphadecimal string to convert"
      )] [string]$base31Num = ""
   )

   $alphabet = "0123456789bcdfghjklmnpqrstvwxyz"
   $inputarray = $base31Num.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(31, $pos)
         $pos++
      }
      $decNum
   } Catch {
   "Error: invalid character"
   }
}

# source: Mirko’s Blog

Examples

PS C:\> convertTo-Base31 1645205
1S6Z4

PS C:\> convertFrom-base31 1S6z4
1645205

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

Related PowerShell Cmdlets

Base36
Wiki - Crockford's Base32 excludes the letters I, L, O and U.


 
Copyright © 1999-2025 windevcluster.com
Some rights reserved