RosettaCodeData/Task/Variable-length-quantity/Julia/variable-length-quantity.jl

36 lines
710 B
Julia
Raw Permalink Normal View History

2023-07-01 11:58:00 -04:00
using Printf
mutable struct VLQ
2026-04-30 12:34:36 -04:00
quant::Vector{UInt8}
2023-07-01 11:58:00 -04:00
end
function VLQ(n::T) where T <: Integer
2026-04-30 12:34:36 -04:00
quant = UInt8.(digits(n, base = 128))
@inbounds for i in 2:lastindex(quant)
quant[i] |= 0x80
end
VLQ(reverse(quant))
2023-07-01 11:58:00 -04:00
end
import Base.UInt64
function Base.UInt64(vlq::VLQ)
2026-04-30 12:34:36 -04:00
quant = reverse(vlq.quant)
n = popfirst!(quant)
p = one(UInt64)
for i in quant
p *= 0x80
n += p * (i & 0x7f)
end
return n
2023-07-01 11:58:00 -04:00
end
const test = [0x00200000, 0x001fffff, 0x00000000, 0x0000007f,
2026-04-30 12:34:36 -04:00
0x00000080, 0x00002000, 0x00003fff, 0x00004000,
0x08000000, 0x0fffffff]
2023-07-01 11:58:00 -04:00
for i in test
2026-04-30 12:34:36 -04:00
vlq = VLQ(i)
j = UInt(vlq)
@printf "0x%-8x => [%-25s] => 0x%x\n" i join(("0x" * string(r, base = 16, pad = 2) for r in vlq.quant), ", ") j
2023-07-01 11:58:00 -04:00
end