0

I'm trying to find a way to convert a number into an array of digits, similar to a character array, and still be able to perform mathematical operations on the array.

My first thought was to convert the number to a string, then to a character array, and then convert the array back to Int32 type. However, this has some unexpected results. For example, [int[]](1024).ToString().ToCharArray() results in the following array:

49
48
50
52

I do get what's happening here - PowerShell is treating the digits as ASCII characters, and converting them into their numeric values. However, that doesn't help me solve my problem.

What's the "right way" to convert numbers into single-digit integer arrays?

2 Answers 2

4

Try this:

[char[]]'1024' | %{$_ - 48}

This will convert the characters to ints of the correct value:

C:\PS> [char[]]'1024' | %{$_ - 48} | %{$_.GetType().Name}
Int32
Int32
Int32
Int32

Here is a "mathy" version that works with an int:

C:\PS> $number = 1024
C:\PS> $numDigits = [math]::Floor([math]::Log10($number)) + 1
C:\PS> $res = @()
C:\PS> for ($i = 0; $i -lt $numDigits; $i++) {$res += $number % 10; $number = [Math]::Floor($number / 10)}
C:\PS> $res[($res.count-1)..0]
1
0
2
4
Sign up to request clarification or add additional context in comments.

2 Comments

Ah, so easy because the ASCII values are all 48 higher than the digit values. Not exactly "pure", but it works!
The other option is to use [Math]::Log10() to determine number of digits and then continuously take modulo 10 and divide by 10.
3

OK.

[int[]][string[]][char[]]'1024'
([int[]][string[]][char[]]'1024').gettype()
1
0
2
4

IsPublic IsSerial Name                                     BaseType                   
-------- -------- ----                                     --------                   
True     True     Int32[]                                  System.Array               

Starting with 1024, cast it to [char[]] to separate the digits. Then cast the chars to string to make the int conversion literal text, rather than ascii code.

Different tack, starting with [int], and minimizing casts:

$n = 1024
$array = [int[]](($n -split '') -ne '')

$array
$array.GetType()


1
0
2
4

IsPublic IsSerial Name                                     BaseType                   
-------- -------- ----                                     --------                   
True     True     Int32[]                                  System.Array               

2 Comments

This works if your number is already a string. Is there a way to do it if it's an integer, preferably without having to do another conversion into a string?
Posted another version

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.