在 SWI-Prolog 中,是否有一种使用 REPL 将数字从一个基数转换为另一个基数的简单方法?

In SWI-Prolog is there an easy way to convert numbers from one base to another using REPL?

在使用 REPL 的 SWI-Prolog 中,可以轻松地将任何基数转换为基数 10,例如

?- X = 16'FF.
X = 255.

?- X = 2'11111111.
X = 255.

然而这失败了。 (没想到它会起作用,但显示了我的想法。)

?- 2'X = 16'FF.
ERROR: Syntax error: Operator expected
ERROR: 
ERROR: ** here **
ERROR: 2'X = 16'FF . 

在 SWI-Prolog 中,您可以使用 r 作为 radix in format/2:

Print integer in radix numeric argument notation. Thus ~16r prints its argument hexadecimal. The argument should be in the range [2, ... , 36]. Lowercase letters are used for digits above 9. The colon modifier may be used to form locale-specific digit groups.

示例:

?- format("~2r", 0xFF).
11111111
true.

这是作为答案发布的评论,因为它需要评论无法做到的格式。

如果您有兴趣捕获输出以表示在程序中使用的原子、字符串、字符或字符代码,那么还有 format/n[=17= 的其他变体] 可以做到这一点。参见:format/3

?- format(atom(Hex),"~2r",0xFF).
Hex = '11111111'.

?- format(string(Hex),"~2r",0xFF).
Hex = "11111111".

?- format(chars(Hex),"~2r",0xFF).
Hex = ['1', '1', '1', '1', '1', '1', '1', '1'].

?- format(codes(Hex),"~2r",0xFF).
Hex = [49, 49, 49, 49, 49, 49, 49, 49].