# Base32hex (rfc 4648)

**URL:** <https://www.ruby-forum.com/t/base32hex-rfc-4648/167406>\
**Category:** Ruby\
**Created:** [May 7, 2009, 3:15pm UTC](https://www.ruby-forum.com/t/base32hex-rfc-4648/167406 "2009-05-07T15:15:55Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![alexd](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/96bed5/32.png) [@alexd](https://www.ruby-forum.com/u/alexd)\
**Post date:** [May 7, 2009, 3:15pm UTC](https://www.ruby-forum.com/t/base32hex-rfc-4648/167406/1 "2009-05-07T15:15:55Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![alexd](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/96bed5/32.png) [@alexd](https://www.ruby-forum.com/u/alexd)\
**Post date:** [May 8, 2009, 2:25am UTC](https://www.ruby-forum.com/t/base32hex-rfc-4648/167406/2 "2009-05-08T02:25:39Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![alexd](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/96bed5/32.png) [@alexd](https://www.ruby-forum.com/u/alexd)\
**Post date:** [May 12, 2009, 12:07pm UTC](https://www.ruby-forum.com/t/base32hex-rfc-4648/167406/3 "2009-05-12T12:07:30Z")

</div>

Nobuyoshi N. wrote:

> module Base32  
> module\_function  
> def encode32hex(str)

…

Thanks very much for your help!

Alex.

---

<div class="post-metadata">

**Author:** ![alexd](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/96bed5/32.png) [@alexd](https://www.ruby-forum.com/u/alexd)\
**Post date:** [May 14, 2009, 11:06pm UTC](https://www.ruby-forum.com/t/base32hex-rfc-4648/167406/4 "2009-05-14T23:06:17Z")

</div>

- Nobuyoshi N. [removed\_email\_address@domain.invalid](mailto: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
