1 ;;; hex-util.el --- Functions to encode/decode hexadecimal string.
3 ;; Copyright (C) 1999, 2001-2015 Free Software Foundation, Inc.
5 ;; Author: Shuhei KOBAYASHI <shuhei@aqua.ocn.ne.jp>
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs 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 GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28 (defmacro hex-char-to-num
(chr)
31 ((and (<= ?a chr
)(<= chr ?f
)) (+ (- chr ?a
) 10))
32 ((and (<= ?A chr
)(<= chr ?F
)) (+ (- chr ?A
) 10))
33 ((and (<= ?
0 chr
)(<= chr ?
9)) (- chr ?
0))
34 (t (error "Invalid hexadecimal digit `%c'" chr
)))))
35 (defmacro num-to-hex-char
(num)
36 `(aref "0123456789abcdef" ,num
)))
38 (defun decode-hex-string (string)
39 "Decode hexadecimal STRING to octet string."
40 (let* ((len (length string
))
41 (dst (make-string (/ len
2) 0))
44 ;; logior and lsh are not byte-coded.
45 ;; (aset dst idx (logior (lsh (hex-char-to-num (aref string pos)) 4)
46 ;; (hex-char-to-num (aref string (1+ pos)))))
47 (aset dst idx
(+ (* (hex-char-to-num (aref string pos
)) 16)
48 (hex-char-to-num (aref string
(1+ pos
)))))
53 (defun encode-hex-string (string)
54 "Encode octet STRING to hexadecimal string."
55 (let* ((len (length string
))
56 (dst (make-string (* len
2) 0))
59 ;; logand and lsh are not byte-coded.
60 ;; (aset dst idx (num-to-hex-char (logand (lsh (aref string pos) -4) 15)))
61 (aset dst idx
(num-to-hex-char (/ (aref string pos
) 16)))
63 ;; (aset dst idx (num-to-hex-char (logand (aref string pos) 15)))
64 (aset dst idx
(num-to-hex-char (%
(aref string pos
) 16)))
71 ;;; hex-util.el ends here