Fastest way to separate the digits of an int into an array in .NET?

后端 未结 11 903
天涯浪人
天涯浪人 2021-01-31 20:07

I want to separate the digits of an integer, say 12345, into an array of bytes {1,2,3,4,5}, but I want the most performance effective way to do that, because my program does tha

11条回答
  •  半阙折子戏
    2021-01-31 20:56

    I haven't benchmarked this or anything, but I think this would be the simplest answer. Correct me if I'm wrong.

        Dim num As Integer = 147483647
        Dim nDigits As Integer = 1 + Convert.ToInt32(Math.Floor(Math.Log10(num)))
        Dim result(nDigits - 1) As Integer
    
        For a As Integer = 1 To nDigits
            result(a - 1) = Int(num / (10 ^ (nDigits - a))) Mod 10
        Next
    

    ** EDIT **

    Revised the function because exponents seem to be very expensive.

    Private Function Calc(ByVal num As Integer) As Integer()
        Dim nDigits As Int64 = 1 + Convert.ToInt64(Math.Floor(Math.Log10(num)))
        Dim result(nDigits - 1) As Integer
        Dim place As Integer = 1
    
        For a As Integer = 1 To nDigits
            result(nDigits - a) = Int(num / place) Mod 10
            place = place * 10
        Next
    
        Return result
    End Function
    

    This benchmarks to around 775k/sec (for numbers 9 digits or less). Drop the maximum digits to 7 and it benches at 885k/s. 5 digits at 1.1m/s.

提交回复
热议问题