Variable-length quantity
This page uses content from Wikipedia. The original article was at Variable-length_quantity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) |
Variable-length quantity
You are encouraged to solve this task according to the task description, using any language you may know.
You are encouraged to solve this task according to the task description, using any language you may know.
Task : Implement some operations with respect to Variable-length Quantity, at least including convertions between normal number on the language and the binary representation of the Variable-length Quantity for that number. Any variants is acceptable.
D
This implements a Variable-length Quantity struct for an ulong integer.
<lang d>module vlq ; private import std.string ;
struct VLQ { // variable length quantity (unsiged long, max 63-bit)
ulong value ; static ulong V2I(ubyte[] v) { return VLQ.init.from(v).value ; } uint extract(ubyte[] v) { ulong t = 0; uint idx = 0, limit = v.length - 1 ; if(8 < limit) limit = 8 ; 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(ubyte[] v) { extract(v) ; return this ; } @property ubyte[] toVLQ() { ubyte[] v = [(0x7f & value)] ; ulong k = value >>> 7 ; while(k > 0) { v ~= (k & 0x7f) | 0x80 ; k >>>= 7 ; } if(v.length > 9) throw new Exception("value too large ") ; return v.reverse ; } @property string toStr() { string s ; foreach(e ; toVLQ) s ~= std.string.format("%02X:", e) ; return "("~s[0..$-1]~")" ; } alias value this ; // this allow VLQ works like ulong, eg add, multiply etc.
}</lang>
test code :
<lang d>import std.stdio ; import vlq ; void main() {
VLQ a = VLQ(0x7f), b = VLQ(0x4000), c ; writefln("a:%8x = %s\nb:%8x = %s\nc:%8x = %s", a.value, a.toStr, b.value, b.toStr, c.value, c.toStr) ; c = a * b ; a = c - 1 ; b = VLQ.init.from(a.toVLQ) ; //write them to a binary file std.file.write("vlqtest.bin", a.toVLQ) ; std.file.append("vlqtest.bin", b.toVLQ) ; std.file.append("vlqtest.bin", c.toVLQ) ; //read them back auto buf = cast(ubyte[]) std.file.read("vlqtest.bin") ; writefln("File length : %d", buf.length) ; for(int i = 0, cnt = 1 ; i < buf.length ; cnt++) { auto k = a.extract(buf[i..$]) ; writefln("%d:%8x = %s", cnt, a.value, a.toStr ) ; i += k ; }
}</lang>
output:
a: 7f = (7F) b: 4000 = (81:80:00) c: 0 = (00) File length : 9 1: 1fbfff = (FE:FF:7F) 2: 1fbfff = (FE:FF:7F) 3: 1fc000 = (FF:80:00)