lib/sixword/lib.rb in sixword-0.2.0 vs lib/sixword/lib.rb in sixword-0.3.0

- old
+ new

@@ -63,11 +63,11 @@ end # omit padding bits, if any int >>= padding * 8 - int + [int, 8 - padding] end # Extract the padding from a word, e.g. 'WORD3' => 'WORD', 3 def self.extract_padding(word) unless word[-1] =~ /[1-7]/ @@ -76,11 +76,12 @@ return word[0...-1], Integer(word[-1]) end def self.decode_6_words_to_bstring(word_array, padding_ok) - int_to_byte_array(decode_6_words(word_array, padding_ok)).map(&:chr).join + int_to_byte_array(*decode_6_words(word_array, padding_ok)). + map(&:chr).join end def self.word_to_bits(word) word = word.upcase return WORDS_HASH.fetch(word) @@ -117,28 +118,64 @@ end parity & 0b11 end + # Given an array of bytes, pack them into a single Integer. + # + # For example: + # + # >> byte_array_to_int([1, 2]) + # => 258 + # + # @param byte_array [Array<Fixnum>] + # + # @return Integer + # def self.byte_array_to_int(byte_array) int = 0 byte_array.each do |byte| int <<= 8 int |= byte end int end - def self.int_to_byte_array(int) + # Given an Integer, unpack it into an array of bytes. + # + # For example: + # + # >> int_to_byte_array(258) + # => [1, 2] + # + # >> int_to_byte_array(258, 3) + # => [0, 1, 2] + # + # @param int [Integer] + # @param length [Integer] (nil) Left zero padded size of byte array to + # return. If not provided, no leading zeroes will be added. + # + # @return Array<Fixnum> + # + def self.int_to_byte_array(int, length=nil) unless int >= 0 raise ArgumentError.new("Not sure what to do with negative numbers") end arr = [] while int > 0 arr << (int & 255) int >>= 8 + end + + # pad to appropriate length with leading zeroes + if length + raise ArgumentError.new("Cannot pad to length < 0") if length < 0 + + while arr.length < length + arr << 0 + end end arr.reverse! arr