How to resolve the algorithm Variable-length quantity step by step in the Tcl programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Variable-length quantity step by step in the Tcl programming language

Table of Contents

Problem Statement

Implement some operations on 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.

With above operations,

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Variable-length quantity step by step in the Tcl programming language

Source code in the tcl programming language

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
}


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"
}


  

You may also check:How to resolve the algorithm Infinity step by step in the Java programming language
You may also check:How to resolve the algorithm Greatest element of a list step by step in the Fancy programming language
You may also check:How to resolve the algorithm Brownian tree step by step in the C# programming language
You may also check:How to resolve the algorithm Sorting algorithms/Quicksort step by step in the Julia programming language
You may also check:How to resolve the algorithm Nth root step by step in the Nu programming language