How to base64encode a BigInt?

I think you probably want something like this (making use of @stevengj’s to_bytes):

julia> function to_bytes(n::BigInt; bigendian::Bool=true)
           bytes = Vector{UInt8}(undef, (Base.GMP.MPZ.sizeinbase(n, 2) + 7) ÷ 8)
           order = bigendian ? Cint(1) : Cint(-1)
           count = Ref{Csize_t}()
           @ccall "libgmp".__gmpz_export(bytes::Ptr{UInt8}, count::Ref{Csize_t}, order::Cint,
                       1::Csize_t, 1::Cint, 0::Csize_t, n::Ref{BigInt})::Ptr{UInt8}
           @assert count[] ≤ length(bytes)
           return resize!(bytes, count[])
       end
to_bytes (generic function with 1 method)

julia> function base64urlencode(x::BigInt)
           @assert x >= 0
           base64urlencode(x == 0 ? [0x0] : to_bytes(x))
       end
base64urlencode (generic function with 2 methods)

julia> function base64urlencode(bytes::Vector{UInt8})
           str = base64encode(bytes)
           return replace(str, '=' => "", '+' => '-', '/' => '_')
       end
base64urlencode (generic function with 2 methods)

julia> base64urlencode(big"0")
"AA"

julia> base64urlencode(big"1234")
"BNI"

julia> base64urlencode(big"999999999")
"O5rJ_w"

Refs:

1 Like