ConvertTo-Digits

Convert an integer into an array of bytes of its individual digits.

This is just a small helper function that I created for myself, but I thought I’d share it in case someone else might find it handy.

function ConvertTo-Digits {
<#
.SYNOPSIS
Convert an integer into an array of bytes of its individual digits.
.DESCRIPTION
Convert an integer into an array of bytes of its individual digits.
.EXAMPLE
ConvertTo-Digits 145
.INPUTS
System.Int32
.NOTES
Author: Øyvind Kallstad
Date: 09.05.2015
Version: 1.0
#>
[OutputType([System.Byte[]])]
[CmdletBinding()]
param(
[Parameter(Position = 0, Mandatory, ValueFromPipeline)]
[ValidateRange(1, [int]::MaxValue)]
[int]$Number
)
$n = $Number
$numberOfDigits = 1 + [convert]::ToInt32([math]::Floor(([math]::Log10($n))))
$digits = New-Object Byte[] $numberOfDigits
for ($i = ($numberOfDigits 1); $i -ge 0; $i) {
$digit = $n % 10
$digits[$i] = $digit
$n = [math]::Floor($n / 10)
}
Write-Output $digits
}

view raw
ConvertTo-Digits.ps1
hosted with ❤ by GitHub

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s