Revisions

gist: 224533 Download_button fork
public
Public Clone URL: git://gist.github.com/224533.git
Embed All Files: show embed
Text #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#!/usr/bin/env ruby
 
def encode_num( number )
  r = {
    :length => 0,
    :buf => []
  }
 
  num = number
 
  puts "encoding number #{number} (#{"%0b" % number})"
  if num == 0 then
    r[:buf] << 0x00
    r[:length] = 1
  else
    r[:length] = 0
 
    while ( num > 0 ) do
      rem = num & 0x7f
      num >>= 7
      if num > 0 then
        rem *= -1
        rem -= 1
      end
      r[:buf] << rem
      r[:length] += 1
      
      puts "Iteration #{r[:length]}"
      puts r[:buf].collect { |b| "%d" % b }.join(' ')
    end
  end
  return r
end
 
def decode_num( buf )
  num = 0
  base = 1
  i = 0
  puts "decoding buf #{buf.join(' ')}"
  while true
    if buf[i] >= 0 then
      num += (buf[i] * base)
      break
    end
    num += (base * (buf[i] + 1) * -1)
    base <<= 7
    i += 1
  end
  return num
end
 
r = encode_num( 23857 )
n = decode_num( r[:buf] )
puts n