Skip to content

Instantly share code, notes, and snippets.

@prodoxx
Created March 8, 2018 12:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prodoxx/391c2336d4c809b3a680737ab7522342 to your computer and use it in GitHub Desktop.
Save prodoxx/391c2336d4c809b3a680737ab7522342 to your computer and use it in GitHub Desktop.
Packs a short string into a Fixnum and vise-versa
class ShortStringPacker
## Packs a short string into a Fixnum
# Arguments:
# str - String object
# Returns: a Fixnum object
def self.pack(str)
abc = [*'a'..'z']
arr = str.chars.map { |x| abc.find_index(x) + 1 }
arr.reduce { |item, key| (item << 5.0) | key }
end
## Unpacks a Fixnum from pack() method into a short string
# Arguments:
# packed - a Fixnum object
# Returns: a String object
def self.unpack(packed)
abc = [*'a'..'z']
binary_string = packed.to_s 2
amt_chars_in_packed = (binary_string.length / 5.0).ceil
binary_string.rjust(amt_chars_in_packed * 5.0, '0')
.to_s
.chars
.each_slice(5)
.map(&:join)
.map! { |x| abc[(x.to_i 2) - 1] }
.join
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment