# How to base64encode a BigInt?

**URL:** <https://discourse.julialang.org/t/how-to-base64encode-a-bigint/96668>\
**Category:** General Usage\
**Tags:** question\
**Created:** [March 27, 2023, 5:14pm UTC](https://discourse.julialang.org/t/how-to-base64encode-a-bigint/96668 "2023-03-27T17:14:35Z")\
**Posts on this page:** 1\
**Showing post:** 5

<div class="post-metadata">

**Author:** ![pfitzseb](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/pfitzseb/32/45566_2.png) [@pfitzseb](https://discourse.julialang.org/u/pfitzseb)\
**Post date:** [March 28, 2023, 8:03am UTC](https://discourse.julialang.org/t/how-to-base64encode-a-bigint/96668/5 "2023-03-28T08:03:16Z")

</div>

I think you probably want something like this (making use of @stevengj’s [`to_bytes`](https://discourse.julialang.org/t/bigint-to-bytes/91107/5)):

```julia
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:

- [RFC 7515: JSON Web Signature (JWS)](https://www.rfc-editor.org/rfc/rfc7515#appendix-C)
- [RFC 7518: JSON Web Algorithms (JWA)](https://www.rfc-editor.org/rfc/rfc7518#section-2)

---

_[View the full topic](https://discourse.julialang.org/t/how-to-base64encode-a-bigint/96668)._
