Reputation: 29
How can I convert a number from a certain base into base 10 in Lisp ? Is any defaut function that can do that ,if not how can I buid that function ?
Upvotes: 1
Views: 863
Reputation: 85883
In a comment on my answer to your earlier question, https://stackoverflow.com/q/33634012/1281433, you (implicitly) asked about this:
I need also to do the reverse function (to convert a number in any base into base 10) and i dont know :(
I replied, hoping you'd visit the documentation, "The Common Lisp HyperSpec is very comprehensive. I'd suggest you look for functions whose names start with parse-." To make this clearer, if you go to P in the index, there's a function parse-integer that does exactly what you're looking for. This is safer, in my opinion, than the approach using *read-base* and read in another answer, since using read opens you up to a bunch of issues (you can read non numbers, there can be read-time evaluation, etc.). parse-integer does just what you're asking for:
(parse-integer "9" :radix 16) ;=> 9
(parse-integer "10" :radix 16) ;=> 16
(parse-integer "1af" :radix 16) ;=> 431
(parse-integer "111" :radix 2) ;=> 7
Upvotes: 6
Reputation: 48765
Base for integers are only interesting in terms of visualization and interpretation. Thus "10" is the visualization of ten in decimal, eight in octal and sixteen in hexadecimal, but the number does not look like that in memory.
You can change representation with *print-base*
:
(let ((*print-base* 8))
(print 10)) ; ==> 10, but displays "12"
Why it prints 12 is because when printing *print-base*
is 8
while the REPL prints the result of the form after the *print-base*
is back to the global value it was. You use *read-base*
for reading numbers:
(let ((*read-base* 16))
(with-input-from-string (in "10") (read in))) ; ==> 16
Upvotes: 3