Class: Packer
- Inherits:
-
Object
- Object
- Packer
- Defined in:
- lib/packer.rb
Class Method Summary collapse
- .pack_big_int(sign, num) ⇒ Object
-
.pack_int(num) ⇒ Object
Format: ESDDDDDD EDDDDDDD EDD…
- .pack_str(str) ⇒ Object
Class Method Details
.pack_big_int(sign, num) ⇒ Object
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/packer.rb', line 52 def self.pack_big_int(sign, num) num_bits = num.to_s(2) first = "1#{sign}#{num_bits[-6..]}" num_bits = num_bits[0..-7] bytes = [] num_bits.chars.groups_of(7).each do |seven_bits| # mark all as extended bytes << "1#{seven_bits.join.rjust(7, '0')}" end # least significant first bytes = bytes.reverse # mark last byte as unextended bytes[-1][0] = '0' ([first] + bytes).map { |b| b.to_i(2) } end |
.pack_int(num) ⇒ Object
Format: ESDDDDDD EDDDDDDD EDD… Extended, Data, Sign
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 |
# File 'lib/packer.rb', line 11 def self.pack_int(num) # the first byte can fit 6 bits # because the first two bits are extended and sign # so if you have a number bigger than 63 # it needs two bytes # which are also least significant byte first etc # so we do not support that YET # # the first too big number 64 is represented as those bits # 10000000 00000001 # ^^^ ^ ^^ ^ # ||\ / | \ / # || \ / not \ / # || \ extended # || \ / # || \ / # || \ / # || \/ # || /\ # || / \ # || / \ # || 0000001 000000 # || | # || v # || 64 # || # |positive # extended sign = '0' if num.negative? sign = '1' num += 1 end num = num.abs return pack_big_int(sign, num) if num > 63 || num < -63 ext = '0' bits = ext + sign + num.to_s(2).rjust(6, '0') [bits.to_i(2)] end |
.pack_str(str) ⇒ Object
69 70 71 |
# File 'lib/packer.rb', line 69 def self.pack_str(str) str.chars.map(&:ord) + [0x00] end |