Skip to content

Instantly share code, notes, and snippets.

@rjollet
Last active March 4, 2016 07:35
Show Gist options
  • Save rjollet/bdce1fdd14a9b95f5b59 to your computer and use it in GitHub Desktop.
Save rjollet/bdce1fdd14a9b95f5b59 to your computer and use it in GitHub Desktop.
class ShortStringPacker
## Packs a short string into a Fixnum
# Arguments:
# str - String object
# Returns: a Fixnum object
def self.pack(str, nb_bits=5)
res = 0
str.each_char.with_index do |char, index|
res = res | ((char.ord - 'a'.ord + 1) << nb_bits*(str.length-(index+1)))
end
res
end
## Unpacks a Fixnum from pack() method into a short string
# Arguments:
# packed - a Fixnum object
# Returns: a String object
def self.unpack(packed, nb_bits=5)
res = ""
mask = (2 ** nb_bits) - 1
(0..packed.to_s(2).length-1).step(nb_bits).reverse_each do |i|
res += (((packed & (mask << i)) >> i) + 'a'.ord - 1) .chr
end
res
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment