Merge from emacs--rel--22
[emacs.git] / lisp / hex-util.el
blobe037e07a29fe0f83db01ecc985af9bad1f8d28b5
1 ;;; hex-util.el --- Functions to encode/decode hexadecimal string.
3 ;; Copyright (C) 1999, 2001, 2002, 2003, 2004,
4 ;; 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
6 ;; Author: Shuhei KOBAYASHI <shuhei@aqua.ocn.ne.jp>
7 ;; Keywords: data
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 3, or (at your option)
14 ;; any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING. If not, write to the
23 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24 ;; Boston, MA 02110-1301, USA.
26 ;;; Commentary:
28 ;;; Code:
30 (eval-when-compile
31 (defmacro hex-char-to-num (chr)
32 `(let ((chr ,chr))
33 (cond
34 ((and (<= ?a chr)(<= chr ?f)) (+ (- chr ?a) 10))
35 ((and (<= ?A chr)(<= chr ?F)) (+ (- chr ?A) 10))
36 ((and (<= ?0 chr)(<= chr ?9)) (- chr ?0))
37 (t (error "Invalid hexadecimal digit `%c'" chr)))))
38 (defmacro num-to-hex-char (num)
39 `(aref "0123456789abcdef" ,num)))
41 (defun decode-hex-string (string)
42 "Decode hexadecimal STRING to octet string."
43 (let* ((len (length string))
44 (dst (make-string (/ len 2) 0))
45 (idx 0)(pos 0))
46 (while (< pos len)
47 ;; logior and lsh are not byte-coded.
48 ;; (aset dst idx (logior (lsh (hex-char-to-num (aref string pos)) 4)
49 ;; (hex-char-to-num (aref string (1+ pos)))))
50 (aset dst idx (+ (* (hex-char-to-num (aref string pos)) 16)
51 (hex-char-to-num (aref string (1+ pos)))))
52 (setq idx (1+ idx)
53 pos (+ 2 pos)))
54 dst))
56 (defun encode-hex-string (string)
57 "Encode octet STRING to hexadecimal string."
58 (let* ((len (length string))
59 (dst (make-string (* len 2) 0))
60 (idx 0)(pos 0))
61 (while (< pos len)
62 ;; logand and lsh are not byte-coded.
63 ;; (aset dst idx (num-to-hex-char (logand (lsh (aref string pos) -4) 15)))
64 (aset dst idx (num-to-hex-char (/ (aref string pos) 16)))
65 (setq idx (1+ idx))
66 ;; (aset dst idx (num-to-hex-char (logand (aref string pos) 15)))
67 (aset dst idx (num-to-hex-char (% (aref string pos) 16)))
68 (setq idx (1+ idx)
69 pos (1+ pos)))
70 dst))
72 (provide 'hex-util)
74 ;; arch-tag: fe8aaa79-6c86-400e-813f-5a8cc4cb3859
75 ;;; hex-util.el ends here