]> code.delx.au - gnu-emacs/blob - lisp/gnus/hex-util.el
Merged in changes from CVS trunk.
[gnu-emacs] / lisp / gnus / hex-util.el
1 ;;; hex-util.el --- Functions to encode/decode hexadecimal string.
2
3 ;; Copyright (C) 1999, 2001 Free Software Foundation, Inc.
4
5 ;; Author: Shuhei KOBAYASHI <shuhei@aqua.ocn.ne.jp>
6 ;; Keywords: data
7
8 ;; This file is part of FLIM (Faithful Library about Internet Message).
9
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.
14
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.
19
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.
24
25 ;;; Commentary:
26
27 ;;; Code:
28
29 (eval-when-compile
30 (defmacro hex-char-to-num (chr)
31 (` (let ((chr (, chr)))
32 (cond
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)))))
39
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))
44 (idx 0)(pos 0))
45 (while (< pos len)
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)))))
51 (setq idx (1+ idx)
52 pos (+ 2 pos)))
53 dst))
54
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))
59 (idx 0)(pos 0))
60 (while (< pos len)
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)))
64 (setq idx (1+ idx))
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)))
67 (setq idx (1+ idx)
68 pos (1+ pos)))
69 dst))
70
71 (provide 'hex-util)
72
73 ;;; arch-tag: fe8aaa79-6c86-400e-813f-5a8cc4cb3859
74 ;;; hex-util.el ends here