Forum: Ruby base32hex (rfc 4648)

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Alex D. (Guest)
on 2009-05-07 17:15
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.
Nobuyoshi N. (Guest)
on 2009-05-08 04:25
(Received via mailing list)
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
Alex D. (Guest)
on 2009-05-12 14:07
Nobuyoshi N. wrote:

> module Base32
>   module_function
>   def encode32hex(str)

...

Thanks very much for your help!


Alex.
Simon K. (Guest)
on 2009-05-15 01:06
(Received via mailing list)
* Nobuyoshi N. <removed_email_address@domain.invalid> (2009-05-08) schrieb:

>     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
This topic is locked and can not be replied to.