Variable-length quantity: Difference between revisions

Content added Content deleted
m (→‎{{header|Phix}}: added syntax colouring the hard way)
(Updated to Nim 1.4: removed import of "unsigned"; added missing parameter type. Also simplified formulas and used "strformat" rather than "strutils".)
Line 1,256: Line 1,256:


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import unsigned, strutils
<lang nim>import strformat


proc toSeq(x: uint64): seq[uint8] =
proc toSeq(x: uint64): seq[uint8] =
var x = x
var x = x
result = @[]
var f = 0u64
for i in countdown(9u64, 1):
var f = 0
if (x and 127'u64 shl (i * 7)) > 0:
for i in countdown(9, 1):
if (x and (127'u64 shl uint((i * 7)))) > 0'u64:
f = i
f = i
break
break
for j in 0..f:
for j in 0u64..f:
result.add(uint8((x shr uint64((f - j) * 7)) and 127) or 128)
result.add uint8((x shr ((f - j) * 7)) and 127) or 128


result[f] = result[f] xor 128'u8
result[f] = result[f] xor 128'u8


proc fromSeq(xs): uint64 =
proc fromSeq(xs: openArray[uint8]): uint64 =
result = 0
for x in xs:
for x in xs:
result = (result shl 7) or (x and 127)
result = (result shl 7) or (x and 127)
Line 1,279: Line 1,277:
0x200000'u64, 0x3311a1234df31413'u64]:
0x200000'u64, 0x3311a1234df31413'u64]:
let c = toSeq(x)
let c = toSeq(x)
echo "seq from $#: $# back: $#".format(x, c, fromSeq(c))</lang>
echo &"seq from {x}: {c} back: {fromSeq(c)}"</lang>

Output:
{{out}}
<pre>seq from 127: @[127] back: 127
<pre>seq from 127: @[127] back: 127
seq from 16384: @[129, 128, 0] back: 16384
seq from 16384: @[129, 128, 0] back: 16384