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.

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

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

# 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


 
Copyright © 1999-2024 SS64.com
Some rights reserved