Update copyright notices for 2013.
[bpt/emacs.git] / lisp / hex-util.el
CommitLineData
06cec913
GM
1;;; hex-util.el --- Functions to encode/decode hexadecimal string.
2
ab422c4d 3;; Copyright (C) 1999, 2001-2013 Free Software Foundation, Inc.
06cec913
GM
4
5;; Author: Shuhei KOBAYASHI <shuhei@aqua.ocn.ne.jp>
6;; Keywords: data
7
8;; This file is part of GNU Emacs.
9
eb3fa2cf 10;; GNU Emacs is free software: you can redistribute it and/or modify
06cec913 11;; it under the terms of the GNU General Public License as published by
eb3fa2cf
GM
12;; the Free Software Foundation, either version 3 of the License, or
13;; (at your option) any later version.
06cec913
GM
14
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.
19
20;; You should have received a copy of the GNU General Public License
eb3fa2cf 21;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
06cec913
GM
22
23;;; Commentary:
24
25;;; Code:
26
27(eval-when-compile
28 (defmacro hex-char-to-num (chr)
29 `(let ((chr ,chr))
30 (cond
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)))
37
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))
42 (idx 0)(pos 0))
43 (while (< pos len)
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)))))
49 (setq idx (1+ idx)
50 pos (+ 2 pos)))
51 dst))
52
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))
57 (idx 0)(pos 0))
58 (while (< pos len)
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)))
62 (setq idx (1+ idx))
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)))
65 (setq idx (1+ idx)
66 pos (1+ pos)))
67 dst))
68
69(provide 'hex-util)
70
06cec913 71;;; hex-util.el ends here