farm ostrich
farm ostrich

Reputation: 5949

Lisp -- How to add several hexadecimal numbers without base conversion?

Ii would like to know how to add several hexadecimal numbers in lisp without first converting them to another base. How could this be done?

Upvotes: 4

Views: 3561

Answers (3)

Rainer Joswig
Rainer Joswig

Reputation: 139251

Common Lisp:

> (setf *print-base* 16)

> (setf *read-base* 16)

> (+ a d)
17

Upvotes: 6

Terje Norderhaug
Terje Norderhaug

Reputation: 3689

Hexadecimal is just a character representation of numbers using digits from 0 to F. The Lisp implementation will typically convert hex numbers into its internal binary representation before addition. You can then print the sum in hex if that's the desired presentation format:

(format T "~x" (+ #xA #x2))

You could write a function that implements the logic for symbolic addition of hexadecimal character digits, like that #\A plus #\2 is #\C, handling carry if you want to go beyond single hex digits. But such a function serves little purpose but as an exercise to demonstrate the algorithm for symbolic hexadecimal addition.

Upvotes: 3

John R. Strohm
John R. Strohm

Reputation: 7667

In GNU Emacs, hexadecimal numbers are tagged with #x.

(+ #x3 #xA)
13

I don't know offhand what Common LISP or Scheme use.

If what you have is something like

125A BD22 34FF

and you want to add them up, you'll have to take an edit pass over them to prepend the #x tags before you wrap them in (+ ...).

(+ #x125A #xBD22 #x34FF)

Upvotes: 4

Related Questions