;; from integer to an string having its hex value

(with (val 1
    tab
    (map List 
      (lambda (n &aux (old-val val)) (setq val (* val 16))
      old-val)
      (make-list 8)
    )
  )
  (setq itox:tab (make-list 8))
  (dotimes (i 8)
    (put itox:tab i (get tab (- 7 i)))
))

(setq itox:digits "0123456789abcdef")

;;AUTOLOAD: itox
;;AUTODOC: itox "integer to hexadecimal representation conversion"
;;(itox number) 
;;
;;Returns a string representing the hexadecimal representation
;;of number, prefixed by 0x
;;e.g.:
;;(itox 678) ==> "0x2a6"

(defun itox (n &aux
    (str (copy "0x"))
    started?
    value
  )
  (if (typep n Int)
    (dolist (digit itox:tab)
      (setq value (mod (/ n digit) 16))
      (if (or started? (/= 0 value))
	(progn
	  (setq started? t)
	  (put str -1 (get itox:digits value))
  ))))
  (if (not started?) (put str -1 #\0))
  str
)
  
;;AUTOLOAD: xtoi
;;AUTODOC: xtoi "hexadecimal to integer representation conversion"
;;(xtoi string)
;;
;; Returns a decimal number read from its hexadecimal
;;representation, prefixed by 0x
;;(xtoi"0x2a6") ==> 678

(defun xtoi (s &aux
    (n 0)
  )  
  (dolist (c s)
    (if
      (and (>= c #\0)(<= c #\9))
      (setq n (+ (* n 16) (- c #\0)))
      
      (and (>= c #\A) (<= c #\F))
      (setq n (+ (* n 16) (- c 55)))
      
      (and (>= c #\a) (<= c #\f))
      (setq n (+ (* n 16) (- c 87)))
    )
  )
  n
)
