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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |