Convert a number to a byte array

You can’t use reinterpret because a BigInt is stored as a pointer and some lengths, but you can get at the raw bytes in a variety of ways, from low-level (exploit the raw pointer) to high-level. The best-documented way is to use the digits! function:

julia> a = big(11)^100
137806123398222701841183371720896367762643312000384664331464775521549852095523076769401159497458526446001

jjulia> digits!(Vector{UInt8}(undef, ndigits(a; base=256)), a, base=256)
44-element Vector{UInt8}:
 0xb1
 0xe1
 0x4f
 0x64
 0xe2
 0x52
 0xe1
    ⋮
 0xcc
 0xf1
 0x0e
 0x71
 0xd8
 0x03

See also the discussion in BigInt to bytes — since that discussion, digits! got optimized using mpz_export as explained in the thread.

What are you trying to accomplish?

4 Likes