[racket-dev] hex decoding?

From: Tony Garnock-Jones (tonyg at ccs.neu.edu)
Date: Mon Jun 10 20:36:42 EDT 2013

Here's the one I've been using in racl (https://github.com/tonyg/racl,
raco pkg install racl). It ignores non-hex characters but is less
efficient than Stephen's version. Um, and it expects *bytes* as input,
not strings. I'm not sure why, actually.


(define (hex-string->bytes . strs)
  (define cleaned (bytes->string/utf-8
                   (regexp-replace* #rx"[^0-9a-fA-F]+"
                                    (apply bytes-append strs)
                                    "")))
  (define count (/ (string-length cleaned) 2))
  (define bs (make-bytes count 0))
  (for ((i (in-range count)))
    (bytes-set! bs i (string->number
		      (substring cleaned (* i 2) (+ 2 (* i 2))) 16)))
  bs)



On 2013-06-09 8:14 PM, Stephen Chang wrote:
> 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
> _________________________
>   Racket Developers list:
>   http://lists.racket-lang.org/dev
> 

Posted on the dev mailing list.