base32hex (rfc 4648)

A

Alex Dd

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.
 
N

Nobuyoshi Nakada

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
 
S

Simon Krahnke

* Nobuyoshi Nakada said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,173
Messages
2,570,939
Members
47,484
Latest member
JackRichard

Latest Threads

Top