将十六进制数转换为 Common Lisp 中的十六进制数表示
我正在尝试将十六进制数转换为十六进制数表示形式。
例如下面的例子。
CL-USER> (foo 0D)
#x0D
我应该使用宏函数吗?
I'm trying to convert hexadecimal number to hexadecimal number presentation.
for example is below.
CL-USER> (foo 0D)
#x0D
Should i use macro function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
0D 是一个符号(默认情况下)。使用 SYMBOL-NAME 作为字符串获取其名称。使用 PARSE-INTEGER 和 :RADIX 16 来获取数字。
如果你没有任何理由,我不会将十六进制数字表示为符号。
0D is a symbol (by default). Get its name with SYMBOL-NAME as a string. Use PARSE-INTEGER with :RADIX 16 to get the number.
If you don't have any reason for it, representing hex numbers as symbols is nothing I would do.
您是说要将数字格式化为十六进制字符串吗?如果是这样,你会想要这样的东西:
(format nil "~x" #x0D)
Are you saying that you want to format a number as a hexadecimal string? If so, you would want something like this:
(format nil "~x" #x0D)
正如您所说的那样,您的问题毫无意义。不存在“十六进制数”这样的东西; “十六进制”是数字表示系统的名称。在您的示例中,输入似乎是一个符号,正如 Rainer 所说,但并非每个这样的“十六进制”都是符号。假设您希望 (foo 10) 的输出为 #x10,而这里的输入是一个数字。因此,如果 Lisp 阅读器将输入解释为(基数 10)数字,那么它应该转换为重新读取基数 16 时得到的数字。
Rainer 忽略的另一点是,如果 0D 被理解为符号,那么 (foo 0D) 将导致 UNBOUND-VARIABLE 错误。您必须编写 (foo '0D) 才能使 0D 成为 foo 的输入。
在输出方面,我认为没有任何本地 Lisp 对象打印为 "#x..." 。如果您希望以 16 为基数打印数字,则可以将 print-base 绑定到 16,但您不会在其前面看到任何 Sharpsign-x。
这表明对您的问题采取了某种不同的方法。我们定义了一个新的数据类型,它确实以 #x 开头打印,并让 foo 构造这样一个对象:
现在我们得到以下结果:
我有一种奇怪的感觉,这不是 Rafael 所要求的!
As phrased your question makes no sense. There is no such thing as a "hexadecimal number"; "hexadecimal" is the name of a number-presentation system. In your example, the input appears to be a symbol, as Rainer says, but not every such "hexadecimal" is a symbol. Presumably you want the output of (foo 10) to be #x10, and here the input is a number. So if the input is interpreted by the Lisp reader as a (base-10) number, then it should be converted to the number you would get if reread base 16.
Another point that Rainer overlooked is that if 0D is understood as a symbol, then (foo 0D) would cause an UNBOUND-VARIABLE error. You would have to write (foo '0D) to make 0D an input to foo.
On the output side, I don't think there is any native Lisp object that prints as "#x..." . If you want numbers to print in base 16, then you bind print-base to 16, but you won't see any sharpsign-x in front of it.
That suggests a somewhat different approach to your problem. We define a new datatype that does print starting with #x, and have foo construct such an object:
Now we get the following:
I have a funny feeling this is not what Rafael was asking!