Code Snippet

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
let toBinary : int -> uint64 -> string =
    fun bits n ->
        let pad : int -> string -> string = fun n x -> x.PadLeft(n,'0')
        let rec loop : (uint64 * string list) -> string list = function
            | 0UL,acc -> acc
            | m  ,acc ->
                let m' = m &&& 1UL
                ( (m-m') >>> 1, string m' :: acc ) |> loop
        ( n, [] ) |> loop |> List.fold (fun acc x -> x + acc) "" |> pad bits

let x64 = toBinary 64
let x32 = toBinary 32
let x16 = toBinary 16
let x8  = toBinary  8

225UL |> x8
225UL |> x16
42UL  |> x32
0UL   |> x64

open System

Int32.MaxValue  |> uint64 |> x32
Int64.MaxValue  |> uint64 |> x64
UInt64.MaxValue           |> x64

Code output:

> 
val toBinary : bits:int -> n:uint64 -> string

> 
val x64 : (uint64 -> string)
val x32 : (uint64 -> string)
val x16 : (uint64 -> string)
val x8 : (uint64 -> string)

> val it : string = "10000111"
> val it : string = "0000000010000111"
> val it : string = "00000000000000000000000000010101"
> val it : string =
  "0000000000000000000000000000000000000000000000000000000000000000"

> val it : string = "01111111111111111111111111111111"
> val it : string =
  "0111111111111111111111111111111111111111111111111111111111111111"
> val it : string =
  "1111111111111111111111111111111111111111111111111111111111111111"

References: