[racket-dev] hex decoding?
There doesn't appear to be a library function for going the reverse
direction but here's one way to write it up:
#lang racket
(define ASCII-ZERO (char->integer #\0))
;; [0-9A-Fa-f] -> Number from 0 to 15
(define (hex-char->number c)
(if (char-numeric? c)
(- (char->integer c) ASCII-ZERO)
(match c
[(or #\a #\A) 10]
[(or #\b #\B) 11]
[(or #\c #\C) 12]
[(or #\d #\D) 13]
[(or #\e #\E) 14]
[(or #\f #\F) 15]
[_ (error 'hex-char->number "invalid hex char: ~a\n" c)])))
(define (hex-string->bytes str) (list->bytes (hex-string->bytelist str)))
(define (hex-string->bytelist str)
(with-input-from-string
str
(thunk
(let loop ()
(define c1 (read-char))
(define c2 (read-char))
(cond [(eof-object? c1) null]
[(eof-object? c2) (list (hex-char->number c1))]
[else (cons (+ (* (hex-char->number c1) 16)
(hex-char->number c2))
(loop))])))))
(require file/sha1)
(hex-string->bytes (bytes->hex-string #"turtles"))
Welcome to DrRacket, version 5.3.4.6 [3m].
Language: racket [custom].
#"turtles"
>
On Sun, Jun 9, 2013 at 6:30 PM, David Vanderson
<david.vanderson at gmail.com> wrote:
> I'm doing some cryptography exercises that involve a lot of hex
> encoding/decoding. I see there's a bytes->hex-string function in file/sha1
> and openssl/sha1, but I can't find a decode function.
>
> Is a hex decode function in the distribution?
>
> Thanks,
> Dave
> _________________________
> Racket Developers list:
> http://lists.racket-lang.org/dev