all tasks

This commit is contained in:
Ingy döt Net 2013-04-11 01:07:29 -07:00
parent b83f433714
commit 68f8f3e56b
14735 changed files with 178959 additions and 0 deletions

View file

@ -0,0 +1,6 @@
Implement some operations on [[wp:Variable-length quantity|variable-length quantities]], at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and ''vice versa''. Any variants are acceptable.
'''Task :''' With above operations,
*convert these two numbers 0x200000 (2097152 in decimal) and 0x1fffff (2097151 in decimal) into sequences of octets (an eight-bit byte);
*display these sequences of octets;
*convert these sequences of octets back to numbers, and check that they are equal to original numbers.

View file

@ -0,0 +1,2 @@
---
note: Data Structures

View file

@ -0,0 +1,92 @@
with Ada.Containers.Vectors;
with Ada.Text_IO;
with Ada.Unchecked_Conversion;
procedure VLQ is
package Nat_IO is new Ada.Text_IO.Integer_IO (Natural);
type Byte is mod 2**8;
package Byte_IO is new Ada.Text_IO.Modular_IO (Byte);
type Int7 is mod 2**7;
package Int7_IO is new Ada.Text_IO.Modular_IO (Int7);
type VLQ_Octet is record
Value : Int7 := 0;
Next : Boolean := True;
end record;
pragma Pack (VLQ_Octet);
for VLQ_Octet'Size use 8;
function VLQ_To_Byte is new Ada.Unchecked_Conversion (VLQ_Octet, Byte);
function Byte_To_VLQ is new Ada.Unchecked_Conversion (Byte, VLQ_Octet);
package VLQ_Vectors is new Ada.Containers.Vectors (Natural, VLQ_Octet);
procedure Hex_Print (Position : in VLQ_Vectors.Cursor) is
Value : Byte := VLQ_To_Byte (VLQ_Vectors.Element (Position));
begin
Ada.Text_IO.Put (':');
Byte_IO.Put (Item => Value, Width => 6, Base => 16);
end Hex_Print;
procedure Print (X : VLQ_Vectors.Vector) is
begin
X.Iterate (Hex_Print'Access);
Ada.Text_IO.New_Line;
end Print;
function To_VLQ (From : Natural) return VLQ_Vectors.Vector is
Result : VLQ_Vectors.Vector;
Current : Natural := From;
Element : VLQ_Octet;
begin
loop
Element.Value := Int7 (Current mod 2**7);
Result.Prepend (Element);
Current := Current / 2**7;
exit when Current = 0;
end loop;
Element := Result.Last_Element;
Element.Next := False;
VLQ_Vectors.Replace_Element (Result, Result.Last, Element);
return Result;
end To_VLQ;
function To_Int (From : VLQ_Vectors.Vector) return Natural is
use type VLQ_Vectors.Cursor;
Result : Natural := 0;
Iterator : VLQ_Vectors.Cursor := From.First;
begin
while Iterator /= VLQ_Vectors.No_Element loop
Result := Result * 2**7;
Result := Result + Natural(VLQ_Vectors.Element (Iterator).Value);
VLQ_Vectors.Next (Iterator);
end loop;
return Result;
end To_Int;
Test : VLQ_Vectors.Vector;
begin
Test := To_VLQ (16#7f#);
Nat_IO.Put (To_Int (Test), 10, 16); Ada.Text_IO.Put (" = ");
Print (Test);
Test := To_VLQ (16#4000#);
Nat_IO.Put (To_Int (Test), 10, 16); Ada.Text_IO.Put (" = ");
Print (Test);
Test := To_VLQ (16#0#);
Nat_IO.Put (To_Int (Test), 10, 16); Ada.Text_IO.Put (" = ");
Print (Test);
Test := To_VLQ (16#3FFFFE#);
Nat_IO.Put (To_Int (Test), 10, 16); Ada.Text_IO.Put (" = ");
Print (Test);
Test := To_VLQ (16#1FFFFF#);
Nat_IO.Put (To_Int (Test), 10, 16); Ada.Text_IO.Put (" = ");
Print (Test);
Test := To_VLQ (16#200000#);
Nat_IO.Put (To_Int (Test), 10, 16); Ada.Text_IO.Put (" = ");
Print (Test);
end VLQ;

View file

@ -0,0 +1,43 @@
#include <stdio.h>
#include <stdint.h>
void to_seq(uint64_t x, uint8_t *out)
{
int i, j;
for (i = 9; i > 0; i--) {
if (x & 127ULL << i * 7) break;
}
for (j = 0; j <= i; j++)
out[j] = ((x >> ((i - j) * 7)) & 127) | 128;
out[i] ^= 128;
}
uint64_t from_seq(uint8_t *in)
{
uint64_t r = 0;
do {
r = (r << 7) | (uint64_t)(*in & 127);
} while (*in++ & 128);
return r;
}
int main()
{
uint8_t s[10];
uint64_t x[] = { 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL};
int i, j;
for (j = 0; j < sizeof(x)/8; j++) {
to_seq(x[j], s);
printf("seq from %llx: [ ", x[j]);
i = 0;
do { printf("%02x ", s[i]); } while ((s[i++] & 128));
printf("] back: %llx\n", from_seq(s));
}
return 0;
}

View file

@ -0,0 +1,7 @@
seq from 7f: [ 7f ] back: 7f
seq from 4000: [ 81 80 00 ] back: 4000
seq from 0: [ 00 ] back: 0
seq from 3ffffe: [ 81 ff ff 7e ] back: 3ffffe
seq from 1fffff: [ ff ff 7f ] back: 1fffff
seq from 200000: [ 81 80 80 00 ] back: 200000
seq from 3311a1234df31413: [ b3 88 e8 a4 b4 ef cc a8 13 ] back: 3311a1234df31413

View file

@ -0,0 +1,85 @@
import std.stdio, std.string, std.file, std.algorithm;
/// Variable length quantity (unsigned long, max 63-bit).
struct VLQ {
ulong value;
// This allows VLQ to work like an ulong.
alias value this;
uint extract(in ubyte[] v) pure
in {
assert(v.length > 0);
} body {
immutable limit = min(v.length - 1, 8);
ulong t = 0;
size_t idx = 0;
while ((idx < limit) && ((v[idx] & 0x80) > 0))
t = (t << 7) | (0x7f & v[idx++]);
if (idx > limit)
throw new Exception(
"Too large for ulong or invalid format.");
else
value = (t << 7) | v[idx];
return idx + 1;
}
VLQ from(in ubyte[] v) pure {
extract(v);
return this;
}
@property ubyte[] toVLQ() const pure {
ubyte[] v = [0x7f & value];
for (ulong k = value >>> 7; k > 0; k >>>= 7)
v ~= (k & 0x7f) | 0x80;
if (v.length > 9)
throw new Exception("Too large value.");
v.reverse();
return v;
}
static ulong[] split(in ubyte[] b) pure {
ulong[] res;
VLQ v;
for (size_t i = 0; i < b.length; ) {
i += v.extract(b[i .. $]);
res ~= v.value;
}
return res;
}
string toString() const /*pure nothrow*/ {
return format("(%(%02X:%))", this.toVLQ);
}
}
void main() { // VLQ demo code.
VLQ a = VLQ(0x7f),
b = VLQ(0x4000),
c;
writefln("a:%8x = %s\nb:%8x = %s\nc:%8x = %s",
a.value, a, b.value, b, c.value, c);
// Some operations.
c = (a + 1) * b;
a = c - 1;
b = VLQ().from(a.toVLQ);
a <<= 1;
// Convert ulong to octet sequence.
writefln("\na:%8x = %s\nb:%8x = %s\nc:%8x = %s",
a.value, a, b.value, b, c.value, c);
// Write them to a binary file.
std.file.write("vlqtest.bin", a.toVLQ ~ b.toVLQ ~ c.toVLQ);
// Read them back.
const buf = cast(ubyte[])std.file.read("vlqtest.bin");
writefln("\nFile length: %d bytes.", buf.length);
// Convert octet sequence to ulongs.
foreach (immutable i, immutable v; VLQ.split(buf))
writefln("%d:%8x = %s", i + 1, v, VLQ(v));
}

View file

@ -0,0 +1,41 @@
function vlq_encode(integer n)
sequence s
s = {}
while n > 0 do
s = prepend(s, #80 * (length(s) > 0) + and_bits(n, #7F))
n = floor(n / #80)
end while
if length(s) = 0 then
s = {0}
end if
return s
end function
function vlq_decode(sequence s)
integer n
n = 0
for i = 1 to length(s) do
n *= #80
n += and_bits(s[i], #7F)
if not and_bits(s[i], #80) then
exit
end if
end for
return n
end function
function svlg(sequence s)
sequence out
out = ""
for i = 1 to length(s) do
out &= sprintf("#%02x:", {s[i]})
end for
return out[1..$-1]
end function
constant testNumbers = { #200000, #1FFFFF, 1, 127, 128 }
sequence s
for i = 1 to length(testNumbers) do
s = vlq_encode(testNumbers[i])
printf(1, "#%02x -> %s -> #%02x\n", {testNumbers[i], svlg(s), vlq_decode(s)})
end for

View file

@ -0,0 +1,16 @@
package main
import (
"fmt"
"encoding/binary"
)
func main() {
buf := make([]byte, binary.MaxVarintLen64)
for _, x := range []int64{0x200000, 0x1fffff} {
v := buf[:binary.PutVarint(buf, x)]
fmt.Printf("%d encodes into %d bytes: %x\n", x, len(v), v)
x, _ = binary.Varint(v)
fmt.Println(x, "decoded")
}
}

View file

@ -0,0 +1,16 @@
final RADIX = 7
final MASK = 2**RADIX - 1
def octetify = { n ->
def octets = []
for (def i = n; i != 0; i >>>= RADIX) {
octets << ((byte)((i & MASK) + (octets.empty ? 0 : MASK + 1)))
}
octets.reverse()
}
def deoctetify = { octets ->
octets.inject(0) { long n, octet ->
(n << RADIX) + ((int)(octet) & MASK)
}
}

View file

@ -0,0 +1,8 @@
def testNumbers = [ 0x200000, 0x1fffff, 1, 127, 128, 589723405834L ]
testNumbers.each { a ->
def octets = octetify(a)
octets.each { printf "0x%02x ", it }; println ()
def a1 = deoctetify(octets)
assert a1 == a
}

View file

@ -0,0 +1,30 @@
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

View file

@ -0,0 +1,5 @@
N=: 128x
v2i=: (N&| N&#./.~ [: +/\ _1 |. N&>)@i.~&a.
i2v=: a. {~ [:;}.@(N+//.@,:N&#.inv)&.>
ifv=: v2i :. i2v
vfi=: i2v :. v2i

View file

@ -0,0 +1,6 @@
require'convert'
numbers=: 16b7f 16b4000 0 16b3ffffe 16b1fffff 200000
av vlq=: vfi numbers
127 129 128 0 0 129 255 255 126 255 255 127 140 154 64
av (vfi 1 2 3 4 5 6) +&.ifv vlq
129 0 129 128 2 3 130 128 128 2 129 128 128 4 140 154 70

View file

@ -0,0 +1,59 @@
public class VLQCode
{
public static byte[] encode(long n)
{
int numRelevantBits = 64 - Long.numberOfLeadingZeros(n);
int numBytes = (numRelevantBits + 6) / 7;
if (numBytes == 0)
numBytes = 1;
byte[] output = new byte[numBytes];
for (int i = numBytes - 1; i >= 0; i--)
{
int curByte = (int)(n & 0x7F);
if (i != (numBytes - 1))
curByte |= 0x80;
output[i] = (byte)curByte;
n >>>= 7;
}
return output;
}
public static long decode(byte[] b)
{
long n = 0;
for (int i = 0; i < b.length; i++)
{
int curByte = b[i] & 0xFF;
n = (n << 7) | (curByte & 0x7F);
if ((curByte & 0x80) == 0)
break;
}
return n;
}
public static String byteArrayToString(byte[] b)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < b.length; i++)
{
if (i > 0)
sb.append(", ");
String s = Integer.toHexString(b[i] & 0xFF);
if (s.length() < 2)
s = "0" + s;
sb.append(s);
}
return sb.toString();
}
public static void main(String[] args)
{
long[] testNumbers = { 2097152, 2097151, 1, 127, 128, 589723405834L };
for (long n : testNumbers)
{
byte[] encoded = encode(n);
long decoded = decode(encoded);
System.out.println("Original input=" + n + ", encoded = [" + byteArrayToString(encoded) + "], decoded=" + decoded + ", " + ((n == decoded) ? "OK" : "FAIL"));
}
}
}

View file

@ -0,0 +1,10 @@
toOctets[n_Integer] :=
StringJoin @@@
Partition[
PadLeft[Characters@IntegerString[n, 16],
2 Ceiling[Plus @@ DigitCount[n, 16]/2], {"0"}], 2]
fromOctets[octets_List] := FromDigits[StringJoin @@ octets, 16]
Grid[{#, toOctets@#, fromOctets[toOctets@#]} & /@ {16^^3ffffe,
16^^1fffff, 16^^200000}]

View file

@ -0,0 +1,24 @@
let to_vlq n =
let a, b = n lsr 7, n land 0x7F in
let rec aux n acc =
let x = (n land 0x7F) lor 0x80
and xs = n lsr 7 in
if xs > 0
then aux xs (x::acc)
else x::acc
in
aux a [b]
let to_num = List.fold_left (fun n x -> n lsl 7 + (x land 0x7F)) 0
let v_rep n =
Printf.printf "%d ->" n;
let seq = to_vlq n in
List.iter (Printf.printf " 0x%02X") seq;
let num = to_num seq in
Printf.printf "-> %d\n%!" num;
assert (n = num)
let _ =
v_rep 0x200000;
v_rep 0x1FFFFF

View file

@ -0,0 +1,28 @@
test: procedure options(main);
declare s character (20) varying;
declare c character (1);
declare v fixed binary (31);
declare (i, k) fixed binary;
get edit (s) (L);
s = trim (s);
v = 0;
do i = 1 to length(s);
c = substr(s, i, 1);
k = index('0123456789abcdef', c);
if k > 0 then v = v*16 + k - 1;
end;
put skip data (s, v);
/* Convert back to hex */
declare hex character(16) initial ('0123456789abcdef');
declare hs character (20) initial ('');
declare d fixed binary;
do i = length(hs) to 1 by -1 until (v = 0);
d = mod(v, 16) + 1;
substr(hs, i, 1) = substr(hex, d, 1);
v = v/16;
end;
put skip list (hs);
end test;

View file

@ -0,0 +1,32 @@
sub vlq_encode ($number is copy) {
my $string = '';
my $t = 0x7F +& $number;
$number +>= 7;
$string = $t.chr ~ $string;
while ($number) {
$t = 0x7F +& $number;
$string = (0x80 +| $t).chr ~ $string;
$number +>= 7;
}
return $string;
}
sub vlq_decode ($string is copy) {
my $number = '0b';
for $string.ords -> $oct {
$number ~= ($oct +& 0x7F).fmt("%07b");
}
return :2($number);
}
#test encoding and decoding
for (
0, 0xa, 123, 254, 255, 256,
257, 65534, 65535, 65536, 65537, 0x1fffff,
0x200000
) -> $testcase {
my $encoded = vlq_encode($testcase);
printf "%8s %12s %8s\n", $testcase,
( join ':', $encoded.ords>>.fmt("%02X") ),
vlq_decode($encoded);
}

View file

@ -0,0 +1,30 @@
use warnings;
use strict;
for my $testcase (
0, 0xa, 123, 254, 255, 256,
257, 65534, 65535, 65536, 65537, 0x1fffff,
0x200000
)
{
my @vlq = vlq_encode($testcase);
printf "%8s %12s %8s\n", $testcase, ( join ':', @vlq ), vlq_decode(@vlq);
}
sub vlq_encode {
my @vlq;
my $binary = sprintf "%s%b", 0 x 7, shift;
$binary =~ s/(.{7})$//;
@vlq = ( unpack 'H2', ( pack 'B8', '0' . $1 ) );
while ( 0 + $binary ) {
$binary =~ s/(.{7})$//;
unshift @vlq, ( unpack 'H2', pack 'B8', '1' . $1 );
}
return @vlq;
}
sub vlq_decode {
my $num;
$num .= sprintf "%07b", hex(shift @_) & 0x7f while @_;
return oct '0b' . $num;
}

View file

@ -0,0 +1,14 @@
(de numToVlq (Num)
(let Res (cons (& Num 127))
(while (gt0 (setq Num (>> 7 Num)))
(push 'Res (| 128 (& Num 127))) )
Res ) )
(de vlqToNum (Vlq)
(let Res 0
(for N Vlq
(setq Res (| (>> -7 Res) (& N 127))) ) ) )
(for Num (0 15 16 127 128 255 2097151 2097152)
(let Vlq (numToVlq Num)
(tab (12 12 12) Num (glue ":" (mapcar hex Vlq)) (vlqToNum Vlq)) ) )

View file

@ -0,0 +1,23 @@
def tobits(n, _group=8, _sep='_', _pad=False):
'Express n as binary bits with separator'
bits = '{0:b}'.format(n)[::-1]
if _pad:
bits = '{0:0{1}b}'.format(n,
((_group+len(bits)-1)//_group)*_group)[::-1]
answer = _sep.join(bits[i:i+_group]
for i in range(0, len(bits), _group))[::-1]
answer = '0'*(len(_sep)-1) + answer
else:
answer = _sep.join(bits[i:i+_group]
for i in range(0, len(bits), _group))[::-1]
return answer
def tovlq(n):
return tobits(n, _group=7, _sep='1_', _pad=True)
def toint(vlq):
return int(''.join(vlq.split('_1')), 2)
def vlqsend(vlq):
for i, byte in enumerate(vlq.split('_')[::-1]):
print('Sent byte {0:3}: {1:#04x}'.format(i, int(byte,2)))

View file

@ -0,0 +1,24 @@
>>> for n in (254, 255, 256, 257, -2+(1<<16), -1+(1<<16), 1<<16, 1+(1<<16), 0x200000, 0x1fffff ):
print('int: %7i bin: %26s vlq: %35s vlq->int: %7i' % (n, tobits(n,_pad=True), tovlq(n), toint(tovlq(n))))
int: 254 bin: 11111110 vlq: 00000001_11111110 vlq->int: 254
int: 255 bin: 11111111 vlq: 00000001_11111111 vlq->int: 255
int: 256 bin: 00000001_00000000 vlq: 00000010_10000000 vlq->int: 256
int: 257 bin: 00000001_00000001 vlq: 00000010_10000001 vlq->int: 257
int: 65534 bin: 11111111_11111110 vlq: 00000011_11111111_11111110 vlq->int: 65534
int: 65535 bin: 11111111_11111111 vlq: 00000011_11111111_11111111 vlq->int: 65535
int: 65536 bin: 00000001_00000000_00000000 vlq: 00000100_10000000_10000000 vlq->int: 65536
int: 65537 bin: 00000001_00000000_00000001 vlq: 00000100_10000000_10000001 vlq->int: 65537
int: 2097152 bin: 00100000_00000000_00000000 vlq: 00000001_10000000_10000000_10000000 vlq->int: 2097152
int: 2097151 bin: 00011111_11111111_11111111 vlq: 01111111_11111111_11111111 vlq->int: 2097151
>>> vlqsend(tovlq(0x200000))
Sent byte 0: 0x80
Sent byte 1: 0x80
Sent byte 2: 0x80
Sent byte 3: 0x01
>>> vlqsend(tovlq(0x1fffff))
Sent byte 0: 0xff
Sent byte 1: 0xff
Sent byte 2: 0x7f
>>>

View file

@ -0,0 +1,30 @@
/*REXX program to test displaying of octets. */
num1=x2d(200000) ; say 'number1='num1 ' [in hex='d2x(num1)"]"
num2=x2d(1fffff) ; say 'number2='num2 ' [in hex='d2x(num2)"]"
num3=2097172 ; say 'number3='num3 ' [in hex='d2x(num3)"]"
num4=2097151 ; say 'number4='num4 ' [in hex='d2x(num4)"]"
say
onum1=octet(num1) ; say 'number1 octet='onum1
onum2=octet(num2) ; say 'number2 octet='onum2
onum3=octet(num3) ; say 'number3 octet='onum3
onum4=octet(num4) ; say 'number4 octet='onum4
say
bnum1=x2d(space(onum1,0)) ; say 'number1='bnum1
bnum2=x2d(space(onum2,0)) ; say 'number2='bnum2
bnum3=x2d(space(onum3,0)) ; say 'number3='bnum3
bnum4=x2d(space(onum4,0)) ; say 'number4='bnum4
say
if num1==bnum1 &,
num2==bnum2 &,
num3==bnum3 &,
num4==bnum4 then say 'numbers are OK'
else say 'trouble in River City'
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────OCTET subroutine────────────────────*/
octet: procedure; parse arg a,_; x=d2x(a) /*convert A to hex octet.*/
do j=length(x) by -2 to 1 /*process little end first.*/
_=substr(x,j-1,2,0) _ /*pad odd hexchars with an 0 on left*/
end /*j*/
return _

View file

@ -0,0 +1,10 @@
[2097152, 2097151].each do |i|
# Encode i => BER
ber = [i].pack("w")
hex = ber.unpack("C*").collect {|c| "%02x" % c}.join(":")
printf "%s => %s\n", i, hex
# Decode BER => j
j = ber.unpack("w").first
i == j or fail "BER not preserve integer"
end

View file

@ -0,0 +1,27 @@
object VlqCode {
def encode(x:Long)={
val result=scala.collection.mutable.Stack[Byte]()
result push (x&0x7f).toByte
var l = x >>> 7
while(l>0){
result push ((l&0x7f)|0x80).toByte
l >>>= 7
}
result.toArray
}
def decode(a:Array[Byte])=a.foldLeft(0L)((r, b) => r<<7|b&0x7f)
def toString(a:Array[Byte])=a map("%02x".format(_)) mkString("[", ", ", "]")
def test(x:Long)={
val enc=encode(x)
println("0x%x => %s => 0x%x".format(x, toString(enc), decode(enc)))
}
def main(args: Array[String]): Unit = {
val xs=Seq(0, 0x7f, 0x80, 0x2000, 0x3fff, 0x4000, 0x1FFFFF, 0x200000, 0x8000000,
0xFFFFFFF, 0xFFFFFFFFL, 0x842FFFFFFFFL, 0x0FFFFFFFFFFFFFFFL)
xs foreach test
}
}

View file

@ -0,0 +1,47 @@
$ include "seed7_05.s7i";
include "bigint.s7i";
const func string: toSequence (in var bigInteger: number) is func
result
var string: sequence is "";
begin
sequence := str(chr(ord(number mod 128_)));
number >>:= 7;
while number <> 0_ do
sequence := str(chr(ord(number mod 128_) + 128)) & sequence;
number >>:= 7;
end while;
end func;
const func bigInteger: fromSequence (in string: sequence) is func
result
var bigInteger: number is 0_;
local
var integer: index is 1;
begin
while ord(sequence[index]) >= 128 do
number <<:= 7;
number +:= bigInteger conv (ord(sequence[index]) - 128);
incr(index);
end while;
number <<:= 7;
number +:= bigInteger conv ord(sequence[index]);
end func;
const proc: main is func
local
const array bigInteger: testValues is [] (
0_, 10_, 123_, 254_, 255_, 256_, 257_, 65534_, 65535_, 65536_, 65537_, 2097151_, 2097152_);
var string: sequence is "";
var bigInteger: testValue is 0_;
var char: element is ' ';
begin
for testValue range testValues do
sequence := toSequence(testValue);
write("sequence from " <& testValue <& ": [ ");
for element range sequence do
write(ord(element) radix 16 lpad0 2 <& " ");
end for;
writeln("] back: " <& fromSequence(sequence));
end for;
end func;

View file

@ -0,0 +1,23 @@
package require Tcl 8.5
proc vlqEncode number {
if {$number < 0} {error "negative not supported"}
while 1 {
lappend digits [expr {$number & 0x7f}]
if {[set number [expr {$number >> 7}]] == 0} break
}
set out [format %c [lindex $digits 0]]
foreach digit [lrange $digits 1 end] {
set out [format %c%s [expr {0x80+$digit}] $out]
}
return $out
}
proc vlqDecode chars {
set n 0
foreach c [split $chars ""] {
scan $c %c c
set n [expr {($n<<7) | ($c&0x7f)}]
if {!($c&0x80)} break
}
return $n
}

View file

@ -0,0 +1,23 @@
proc numtohex {num} {
binary scan [string trimleft [binary format W $num] \0] H* hexEncoded
regsub -all "..(?=.)" $hexEncoded "&:"
}
proc strtohex {string} {
binary scan $string H* hexEncoded
regsub -all "..(?=.)" $hexEncoded "&:"
}
foreach testcase {
123
254 255 256 257
65534 65535 65536 65537
2097152 2097151
12345678901234566789
} {
set encoded [vlqEncode $testcase]
binary scan $encoded H* hexEncoded
regsub -all {..(?=.)} $hexEncoded &: hexEncoded
set decoded [vlqDecode $encoded]
puts "$testcase ([numtohex $testcase]) ==>\
[strtohex $encoded] ([string length $encoded] bytes) ==>\
$decoded"
}