Base conversions in Scheme

By: on March 8, 2006

For a particular protocol we’re implementing, we need to fit some possibly large serial numbers (in the millions) into a rather limited number of characters (5); the answer, naturally, is to encode the number.

To give ourselves room, we decided to use base 64. Jakarta Commons has some handy codec classes, which saves us the number-to-character translation; so all we need is to convert our serial numbers into bytes.

For that, Tony came up with this pretty one liner in Scheme:

(define (number->bytes num) (unfold zero? (cut remainder <> 256) (cut quotient <> 256) num)

The body works in general for base conversions 10 -> something; for example,

(unfold zero? (cut remainder <> 16) (cut quotient <> 16) 257) -> (1 0 1)

Share

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*