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

34 lines
752 B
Text
Raw Permalink Normal View History

2020-02-17 23:21:07 -08:00
using Printf
2018-06-22 20:57:24 +00:00
mutable struct VLQ
quant::Vector{UInt8}
2015-11-18 06:14:39 +00:00
end
2018-06-22 20:57:24 +00:00
function VLQ(n::T) where T <: Integer
quant = UInt8.(digits(n, 128))
@inbounds for i in 2:length(quant) quant[i] |= 0x80 end
VLQ(reverse(quant))
2015-11-18 06:14:39 +00:00
end
2018-06-22 20:57:24 +00:00
import Base.UInt64
function Base.UInt64(vlq::VLQ)
quant = reverse(vlq.quant)
n = shift!(quant)
p = one(UInt64)
for i in quant
2015-11-18 06:14:39 +00:00
p *= 0x80
2018-06-22 20:57:24 +00:00
n += p * ( i & 0x7f)
2015-11-18 06:14:39 +00:00
end
return n
end
2018-06-22 20:57:24 +00:00
const test = [0x00200000, 0x001fffff, 0x00000000, 0x0000007f,
0x00000080, 0x00002000, 0x00003fff, 0x00004000,
0x08000000, 0x0fffffff]
2015-11-18 06:14:39 +00:00
for i in test
2018-06-22 20:57:24 +00:00
vlq = VLQ(i)
j = UInt(vlq)
@printf "0x%-8x => [%-25s] => 0x%x\n" i join(("0x" * hex(r, 2) for r in vlq.quant), ", ") j
2015-11-18 06:14:39 +00:00
end