Base conversions in Scheme
March 8th, 2006 mikeb
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)
Entry Filed under: Technology, Programming
Leave a Comment
Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>
Trackback this post | Subscribe to the comments via RSS Feed