1 ;;; hex-util.el --- Functions to encode/decode hexadecimal string.
3 ;; Copyright (C) 1999, 2001 Free Software Foundation, Inc.
5 ;; Author: Shuhei KOBAYASHI <shuhei@aqua.ocn.ne.jp>
8 ;; This file is part of FLIM (Faithful Library about Internet Message).
10 ;; This program is free software; you can redistribute it and/or
11 ;; modify it under the terms of the GNU General Public License as
12 ;; published by the Free Software Foundation; either version 2, or
13 ;; (at your option) any later version.
15 ;; This program is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with this program; see the file COPYING. If not, write to
22 ;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
30 (defmacro hex-char-to-num (chr)
31 (` (let ((chr (, chr)))
33 ((and (<= ?a chr)(<= chr ?f)) (+ (- chr ?a) 10))
34 ((and (<= ?A chr)(<= chr ?F)) (+ (- chr ?A) 10))
35 ((and (<= ?0 chr)(<= chr ?9)) (- chr ?0))
36 (t (error "Invalid hexadecimal digit `%c'" chr))))))
37 (defmacro num-to-hex-char (num)
38 (` (aref "0123456789abcdef" (, num)))))
40 (defun decode-hex-string (string)
41 "Decode hexadecimal STRING to octet string."
42 (let* ((len (length string))
43 (dst (make-string (/ len 2) 0))
46 ;;; logior and lsh are not byte-coded.
47 ;;; (aset dst idx (logior (lsh (hex-char-to-num (aref string pos)) 4)
48 ;;; (hex-char-to-num (aref string (1+ pos)))))
49 (aset dst idx (+ (* (hex-char-to-num (aref string pos)) 16)
50 (hex-char-to-num (aref string (1+ pos)))))
55 (defun encode-hex-string (string)
56 "Encode octet STRING to hexadecimal string."
57 (let* ((len (length string))
58 (dst (make-string (* len 2) 0))
61 ;;; logand and lsh are not byte-coded.
62 ;;; (aset dst idx (num-to-hex-char (logand (lsh (aref string pos) -4) 15)))
63 (aset dst idx (num-to-hex-char (/ (aref string pos) 16)))
65 ;;; (aset dst idx (num-to-hex-char (logand (aref string pos) 15)))
66 (aset dst idx (num-to-hex-char (% (aref string pos) 16)))
73 ;;; hex-util.el ends here