RosettaCodeData/Task/Variable-length-quantity/Icon/variable-length-quantity.icon

31 lines
871 B
Plaintext

procedure main()
every i := 2097152 | 2097151 | 1 | 127 | 128 | 589723405834 | 165 | 256 do
write(image(i)," = ",string2hex(v := uint2vlq(i))," = ",vlq2uint(v))
end
procedure vlq2uint(s) #: decode a variable length quantity
if *s > 0 then {
i := 0
s ? while h := ord(move(1)) do {
if (pos(0) & h > 128) | (not pos(0) & h < 128) then fail
i := 128 * i + h % 128
}
return i
}
end
procedure uint2vlq(i,c) #: encode a whole number as a variable length quantity
if "integer" == type(-1 < i) then
return if i = 0 then
char((/c := 0)) | ""
else
uint2vlq(i/128,1) || char((i % 128) + ((/c := 0) | 128) )
end
procedure string2hex(s) #: convert a string to hex
h := ""
every i := ord(!s) do
h ||:= "0123456789abcdef"[i/16+1] || "0123456789abcdef"[i%16+1]
return h
end