且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-19 23:24:20

在 SWI-Prolog 中,您可以在 format/2:

以基数数字参数表示法打印整数.因此 ~16r 以十六进制打印其参数.参数应该在 [2, ... , 36] 范围内.小写字母用于 9 以上的数字.冒号修饰符可用于形成特定于区域设置的数字组.

示例:

?- 格式(~2r",0xFF).11111111真的.

In SWI-Prolog using the REPL, one can get easily convert from any base to base 10, e.g.

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

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

However this fails. (Didn't expect it to work, but shows what I am thinking.)

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

In SWI-Prolog, you can use r for 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.

Example:

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