Module: TTFunk::BinUtils

Extended by:
BinUtils
Included in:
BinUtils
Defined in:
lib/ttfunk/bin_utils.rb,
lib/ttfunk/bin_utils.rb

Overview

Bit crunching utility methods.

Instance Method Summary collapse

Instance Method Details

#rangify(values) ⇒ Array<Array(Integer, Integer)>

Turns a (sorted) sequence of values into a series of two-element arrays where the first element is the start and the second is the length.

Parameters:

  • values (Array<Integer>)

Returns:

  • (Array<Array(Integer, Integer)>)
Source Code
lib/ttfunk/bin_utils.rb, line 60
60
def rangify(values)
61
  values
62
    .slice_when { |a, b| b - a > 1 }
63
    .map { |span| [span.first, span.length - 1] }
64
end

#slice_int(value, bit_width:, slice_count:) ⇒ Array<Integer>

Slice a big integer into a bunch of small integers. Assumes big-endian.

Parameters:

  • value (Integer)
  • bit_width (Integer)

    bit width of the elements

  • slice_count (Integer)

    number of elements to slice into. This is needed for cases where top bits are zero.

Returns:

  • (Array<Integer>)
Source Code
lib/ttfunk/bin_utils.rb, line 30
30
def slice_int(value, bit_width:, slice_count:)
31
  mask = (2**bit_width) - 1
32
33
  Array.new(slice_count) do |i|
34
    (value >> (bit_width * i)) & mask
35
  end
36
end

#stitch_int(arr, bit_width:) ⇒ Integer

Turn a bunch of small integers into one big integer. Assumes big-endian.

Parameters:

  • arr (Array<Integer>)
  • bit_width (Integer)

    bit width of the elements

Returns:

  • (Integer)
Source Code
lib/ttfunk/bin_utils.rb, line 13
13
def stitch_int(arr, bit_width:)
14
  value = 0
15
16
  arr.each_with_index do |element, index|
17
    value |= element << (bit_width * index)
18
  end
19
20
  value
21
end

#twos_comp_to_int(num, bit_width:) ⇒ Integer

Two’s compliment to an integer.

Parameters:

  • num (Integer)
  • bit_width (Integer)

    number width

Returns:

  • (Integer)
Source Code
lib/ttfunk/bin_utils.rb, line 43
43
def twos_comp_to_int(num, bit_width:)
44
  if num >> (bit_width - 1) == 1
45
    # we want all ones
46
    mask = (2**bit_width) - 1
47
48
    # find 2's complement, i.e. flip bits (xor with mask) and add 1
49
    -((num ^ mask) + 1)
50
  else
51
    num
52
  end
53
end