variable_length_quantity.sf 654 B

12345678910111213141516171819202122232425262728293031323334
  1. #!/usr/bin/ruby
  2. #
  3. ## https://rosettacode.org/wiki/Variable-length_quantity
  4. #
  5. func vlq_encode(num) {
  6. var t = (0x7F & num)
  7. var str = t.chr
  8. while (num >>= 7) {
  9. t = (0x7F & num)
  10. str += chr(0x80 | t)
  11. }
  12. str.reverse
  13. }
  14.  
  15. func vlq_decode(str) {
  16. var num = ''
  17. str.each_byte { |b|
  18. num += ('%07b' % (b & 0x7F))
  19. }
  20. Num(num, 2)
  21. }
  22.  
  23. var tests = [0, 0xa, 123, 254, 255, 256,
  24. 257, 65534, 65535, 65536, 65537, 0x1fffff,
  25. 0x200000]
  26.  
  27. tests.each { |t|
  28. var vlq = vlq_encode(t)
  29. printf("%8s %12s %8s\n", t,
  30. vlq.bytes.join(':', { "%02X" % _ }), vlq_decode(vlq))
  31. }