3

I want to convert a given integer into a base 4 string. For eg : In scala,

var str: String = Integer.toString(10, 4)
gives the output "22"  ie 2*(4^1) + 2*(4^0) = 10

Im having difficulty doing this in F#. Any help is appreciated

Martijn
  • 11,964
  • 12
  • 50
  • 96
tiny m
  • 123
  • 2
  • 1
    Does this provide an answer? https://stackoverflow.com/a/10981113/14134059 Often with fairly commonly computing questions in F# there is an adequate C# solution that can be readily adapted by straight translation. – tranquillity Oct 27 '20 at 01:49
  • 1
    Huh, I was going to say System.Convert, but it only works with base 2, 8, 10, and 16. https://learn.microsoft.com/en-us/dotnet/api/system.convert.tostring?view=netcore-3.1#System_Convert_ToString_System_Int32_System_Int32_ – EricP Oct 27 '20 at 14:58

1 Answers1

0
let intToDigits baseN value : int list =
    let rec loop num digits =
        let q = num / baseN
        let r = num % baseN
        if q = 0 then 
            r :: digits 
        else 
            loop q (r :: digits)

    loop value []

254
|> intToDigits 16
|> List.fold (fun acc x -> acc + x.ToString("X")) ""
|> printfn "%s"

254
|> intToDigits 4
|> List.fold (fun acc x -> acc + x.ToString()) ""
|> printfn "%s"

This outputs FE for the base-16 conversion and 3332 for the base-4 conversion. Note that ToString("X") works for up to base 16, so it could be used for the base-4 conversion too.

I adapted this int based solution from Stuart Lang's bigint example (which uses bigint.DivRem rather than integer operators).

jltrem
  • 12,124
  • 4
  • 40
  • 50