Class: FFXCodec::Encoder

Inherits:
Object
  • Object
show all
Defined in:
lib/ffxcodec/encoder.rb

Overview

Encode two integers into one larger integer and decode back

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(a_size = 32, b_size = 32) ⇒ Encoder

Returns a new instance of Encoder.

Parameters:

  • a_size (Fixnum) (defaults to: 32)

    the number of bits allocated to the left integer

  • b_size (Fixnum) (defaults to: 32)

    the number of bits allocated to the right integer



15
16
17
18
19
20
21
# File 'lib/ffxcodec/encoder.rb', line 15

def initialize(a_size = 32, b_size = 32)
  @a_size = a_size
  @b_size = b_size
  @a_max, @b_max = maximums(a_size, b_size)
  @size = a_size + b_size
  check_size
end

Instance Attribute Details

#a_maxFixnum (readonly)

Returns maximum unsigned value representable by left integer.

Returns:

  • (Fixnum)

    maximum unsigned value representable by left integer



8
9
10
# File 'lib/ffxcodec/encoder.rb', line 8

def a_max
  @a_max
end

#b_maxFixnum (readonly)

Returns maximum unsigned value representable by right integer.

Returns:

  • (Fixnum)

    maximum unsigned value representable by right integer



11
12
13
# File 'lib/ffxcodec/encoder.rb', line 11

def b_max
  @b_max
end

#sizeFixnum (readonly)

Returns size of encoded integer in bits (32 or 64).

Returns:

  • (Fixnum)

    size of encoded integer in bits (32 or 64)



5
6
7
# File 'lib/ffxcodec/encoder.rb', line 5

def size
  @size
end

Instance Method Details

#decode(c) ⇒ Array<Fixnum>

Separate an unsigned integer into two smaller unsigned integers

Examples:

Decode an encoded 64-bit integer into 40 and 24-bit integers

i = Encoder.new(40, 24)
i.decode(20712612157194244)  #=> [1234567890, 4]

Parameters:

  • c (Fixnum, Bignum)

    encoded value to decode

Returns:

  • (Array<Fixnum>)

    decoded integers



47
48
49
50
51
52
# File 'lib/ffxcodec/encoder.rb', line 47

def decode(c)
  i = interlace(c)
  a = i >> @b_size
  b = (i ^ (a << @b_size))
  [a, b]
end

#encode(a, b) ⇒ Fixnum, Bignum

Combine two unsigned integers into a single, larger unsigned integer

Examples:

Encode 40 and 24-bit integers into a single 64-bit integer

i = Encoder.new(40, 24)
i.encode(1234567890, 4)      #=> 20712612157194244

Parameters:

  • a (Fixnum)

    value to encode

  • b (Fixnum)

    value to encode

Returns:

  • (Fixnum, Bignum)

    encoded integer



33
34
35
36
37
# File 'lib/ffxcodec/encoder.rb', line 33

def encode(a, b)
  check_ab_bounds(a, b)
  i = (a << @b_size) ^ b
  interlace(i)
end