Nyquist / XLISP 2.0  -  Contents | Tutorials | Examples | Reference

Hexadecimal Integer Numbers


XLISP provides the #x read-macro for hexadecimal numbers:

#x0  => 0        #x8  => 8         #x10  => 16
#x1  => 1        #x9  => 9         #x11  => 17
#x2  => 2        #xa  => 10        #x12  => 18
#x3  => 3        #xb  => 11        #x13  => 19
#x4  => 4        #xc  => 12        #x14  => 20
#x5  => 5        #xd  => 13        #x15  => 21
#x6  => 6        #xe  => 14        #x16  => 22
#x7  => 7        #xf  => 15        #x17  => 23

(hex-string integer [all])
integer - an integer expression
all - a boolean expression
returns - the integer in hexadecimal form as string

(defun hex-string (integer &optional all)
  (if (integerp integer)
      (let ((fmt (if all
                     (or (dolist (bits '(16 32 64 128) nil)
                           (let ((fixnum (round (expt 2.0 (1- bits)))))
                             (and (plusp (1- fixnum))
                                  (minusp fixnum)
                                  (return (format nil "%.~ax" (/ bits 4))))))
                         (error "integer limit not found"))
                     "%x")))
        (progv '(*integer-format*) (list fmt)
          (format nil "~a" integer)))
      (error "not an integer" integer)))

The 'hex-string' function converts the 'integer' argument into hexadecimal form and returns is as a string. If the optional 'all' argument is not given or NIL, leading zeros are not included in the string. If the optional 'all' argument is non-NIL, all digits of the internal representation of the 'integer' argument, including leading zeros, are contained in the string. This is useful for debugging integer overflow and bit-wise functions.

(hex integer [all])
integer - an integer expression
all - a boolean expression
prints - the integer in hexadecimal form
returns - the integer argument

(defun hex (integer &optional all)
  (if (integerp integer)
      (format t "#x~a~%" (hex-string integer all))
      (format t ";; not an integer~%"))
  integer)

The 'hex' function prints the 'integer' argument in hexadecimal form on the screen. Together with the #x read-macro this can be used for interactive hexadecimal computations.

> (hex 12345678)
#xbc614e
12345678

> (hex (+ #x1f #xa3))
#xc2
194

  Back to top


Nyquist / XLISP 2.0  -  Contents | Tutorials | Examples | Reference