hex-util.el 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. ;;; hex-util.el --- Functions to encode/decode hexadecimal string.
  2. ;; Copyright (C) 1999, 2001-2012 Free Software Foundation, Inc.
  3. ;; Author: Shuhei KOBAYASHI <shuhei@aqua.ocn.ne.jp>
  4. ;; Keywords: data
  5. ;; This file is part of GNU Emacs.
  6. ;; GNU Emacs is free software: you can redistribute it and/or modify
  7. ;; it under the terms of the GNU General Public License as published by
  8. ;; the Free Software Foundation, either version 3 of the License, or
  9. ;; (at your option) any later version.
  10. ;; GNU Emacs is distributed in the hope that it will be useful,
  11. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ;; GNU General Public License for more details.
  14. ;; You should have received a copy of the GNU General Public License
  15. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  16. ;;; Commentary:
  17. ;;; Code:
  18. (eval-when-compile
  19. (defmacro hex-char-to-num (chr)
  20. `(let ((chr ,chr))
  21. (cond
  22. ((and (<= ?a chr)(<= chr ?f)) (+ (- chr ?a) 10))
  23. ((and (<= ?A chr)(<= chr ?F)) (+ (- chr ?A) 10))
  24. ((and (<= ?0 chr)(<= chr ?9)) (- chr ?0))
  25. (t (error "Invalid hexadecimal digit `%c'" chr)))))
  26. (defmacro num-to-hex-char (num)
  27. `(aref "0123456789abcdef" ,num)))
  28. (defun decode-hex-string (string)
  29. "Decode hexadecimal STRING to octet string."
  30. (let* ((len (length string))
  31. (dst (make-string (/ len 2) 0))
  32. (idx 0)(pos 0))
  33. (while (< pos len)
  34. ;; logior and lsh are not byte-coded.
  35. ;; (aset dst idx (logior (lsh (hex-char-to-num (aref string pos)) 4)
  36. ;; (hex-char-to-num (aref string (1+ pos)))))
  37. (aset dst idx (+ (* (hex-char-to-num (aref string pos)) 16)
  38. (hex-char-to-num (aref string (1+ pos)))))
  39. (setq idx (1+ idx)
  40. pos (+ 2 pos)))
  41. dst))
  42. (defun encode-hex-string (string)
  43. "Encode octet STRING to hexadecimal string."
  44. (let* ((len (length string))
  45. (dst (make-string (* len 2) 0))
  46. (idx 0)(pos 0))
  47. (while (< pos len)
  48. ;; logand and lsh are not byte-coded.
  49. ;; (aset dst idx (num-to-hex-char (logand (lsh (aref string pos) -4) 15)))
  50. (aset dst idx (num-to-hex-char (/ (aref string pos) 16)))
  51. (setq idx (1+ idx))
  52. ;; (aset dst idx (num-to-hex-char (logand (aref string pos) 15)))
  53. (aset dst idx (num-to-hex-char (% (aref string pos) 16)))
  54. (setq idx (1+ idx)
  55. pos (1+ pos)))
  56. dst))
  57. (provide 'hex-util)
  58. ;;; hex-util.el ends here