Base32hex (rfc 4648)


#1

Hi -

Does anyone know if there is existing Ruby code which implements
base32hex encoding (defined in RFC 4648)? I couldn’t find one with
google…

Thanks very much for your help!

Alex.


#2

Hi,

At Thu, 7 May 2009 22:15:57 +0900,
Alex Dd wrote in [ruby-talk:336035]:

Does anyone know if there is existing Ruby code which implements
base32hex encoding (defined in RFC 4648)? I couldn’t find one with
google…

module Base32
module_function
def encode32hex(str)
str.gsub(/\G(.{5})|(.{1,4}\z)/mn) do
full = $1; frag = $2
n, c = (full || frag.ljust(5, “\0”)).unpack(“NC”)
full = ((n << 8) | c).to_s(32).rjust(8, “0”)
if frag
full[0, (frag.length*8+4).div(5)].ljust(8, “=”)
else
full
end
end
end

HEX = ‘[0-9a-v]’
def decode32hex(str)
str.gsub(/\G\s*(#{HEX}{8}|#{HEX}{7}=|#{HEX}{5}={3}|#{HEX}{4}={4}|#{HEX}{2}={6}|(\S))/imno)
do
raise “invalid base32” if $2
s = $1
s.tr("=", “0”).to_i(32).divmod(256).pack(“NC”)[0,
(s.count("^=")*5).div(8)]
end
end
end


#3

Nobuyoshi N. wrote:

module Base32
module_function
def encode32hex(str)

Thanks very much for your help!

Alex.


#4
str.gsub(/\G(.{5})|(.{1,4}\z)/mn) do
  full = $1; frag = $2

Great, natural but explicit usage of Ruby’s MatchData object and
parallel
assignment!

mfg, simon … cg