Module: Id3Taginator::Util::MathUtil

Defined in:
lib/id3taginator/util/math_util.rb

Class Method Summary collapse

Class Method Details

.from_32_synchsafe_integer(num) ⇒ String

converts an integer to a 4 byte synchsafe array

Parameters:

  • num (Integer)

    given integer to convert

Returns:

  • (String)

    4 byte String representing the 4 byte synchsafe integer (str.bytes)



27
28
29
30
31
32
33
34
35
# File 'lib/id3taginator/util/math_util.rb', line 27

def self.from_32_synchsafe_integer(num)
  bytes = Array.new(4, 0)
  bytes.each_with_index do |_, index|
    # noinspection RubyMismatchedParameterType
    bytes[(0 - index).abs], num = num.divmod(128**(4 - 1 - index))
  end

  bytes.map(&:chr).join
end

.from_number(integer, padding_to = 0, char = '0') ⇒ String

converts the given number to a byte array, optionally it can be padded using the given char e.g. given 5 and padding 6 will be 00 00 05 and converted to a byte array string

Parameters:

  • integer (Integer)

    the integer to convert

  • padding_to (Integer) (defaults to: 0)

    pad with char if the given number in hex form has less chars than padding_to

  • char (String) (defaults to: '0')

    the character to pad

Returns:

  • (String)

    the returning byte array in String representation



63
64
65
# File 'lib/id3taginator/util/math_util.rb', line 63

def self.from_number(integer, padding_to = 0, char = '0')
  integer.to_s(16).rjust(padding_to, char).scan(/../).map { |x| x.hex.chr }.join
end

.to_32_synchsafe_integer(bytes) ⇒ Integer

converts a 4 byte synchsafe array to an integer

Parameters:

  • bytes (Array<Integer>, nil)

    4 byte array to convert

Returns:

  • (Integer)

    the 32 bit synchsafe integer

Raises:

  • (ArgumentError)


11
12
13
14
15
16
17
18
19
20
# File 'lib/id3taginator/util/math_util.rb', line 11

def self.to_32_synchsafe_integer(bytes)
  raise ArgumentError, 'Input can\'t be nil.' if bytes.nil?

  size = 0
  bytes&.each_with_index do |byte, index|
    size += 128**(4 - 1 - index) * (byte & 0x7f)
  end

  size
end

.to_number(bytes) ⇒ Integer

converts a given byte array to the integer representation

noinspection RubyNilAnalysis

Parameters:

  • bytes (Array<Integer>, nil)

    byte array to convert

Returns:

  • (Integer)

    the integer

Raises:

  • (ArgumentError)


43
44
45
46
47
48
49
50
51
52
53
# File 'lib/id3taginator/util/math_util.rb', line 43

def self.to_number(bytes)
  raise ArgumentError, 'Input can\'t be nil.' if bytes.nil?

  size = 0
  num_bytes = bytes.length
  bytes.each_with_index do |byte, index|
    size += 256**(num_bytes - 1 - index) * (byte & 0xff)
  end

  size
end