Module: TTFunk::BinUtils

Extended by:
BinUtils
Included in:
BinUtils
Defined in:
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)>)


58
59
60
61
62
# File 'lib/ttfunk/bin_utils.rb', line 58

def rangify(values)
  values
    .slice_when { |a, b| b - a > 1 }
    .map { |span| [span.first, span.length - 1] }
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>)


28
29
30
31
32
33
34
# File 'lib/ttfunk/bin_utils.rb', line 28

def slice_int(value, bit_width:, slice_count:)
  mask = (2**bit_width) - 1

  Array.new(slice_count) do |i|
    (value >> (bit_width * i)) & mask
  end
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)


11
12
13
14
15
16
17
18
19
# File 'lib/ttfunk/bin_utils.rb', line 11

def stitch_int(arr, bit_width:)
  value = 0

  arr.each_with_index do |element, index|
    value |= element << (bit_width * index)
  end

  value
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)


41
42
43
44
45
46
47
48
49
50
51
# File 'lib/ttfunk/bin_utils.rb', line 41

def twos_comp_to_int(num, bit_width:)
  if num >> (bit_width - 1) == 1
    # we want all ones
    mask = (2**bit_width) - 1

    # find 2's complement, i.e. flip bits (xor with mask) and add 1
    -((num ^ mask) + 1)
  else
    num
  end
end