首页 > 解决方案 > 将二进制转换为十进制谓词

问题描述

convertBinToDec(B,D):- atom_number(S,B),
                       atom_length(S,L),
                       sub_atom(S, 0, 1, After,S1),
                       atom_number(S1,N),
                       L1 is L-1,
                       sub_atom(S, 1,L1, After ,S2),
                       atom_number(S2,B2),
                       convertBinToDec(B2,D1),
                       D is D1+((2*N)**L1).
convertBinToDec(0,0).
convertBinToDec(1,1).

谓词接受 B ,它是整数形式的二进制数,应该返回 D 其对应的十进制形式,对不起,我对声明性编程语言还是新手,但我不知道为什么我上面的代码总是给出错误,我觉得有问题带有基本情况也不允许使用 prolog 库

标签: prologswi-prologlist

解决方案


Given that Prolog supports expressing binary numbers using the 0b prefix, e.g. 0b10011101, you can use the standard number_codes/2 predicate to perform the conversion:

convert_binary_to_decimal(Binary, Decimal) :-
    number_codes(Binary, Codes),
    number_codes(Decimal, [0'0, 0'b| Codes]).

Sample call:

| ?- convert_binary_to_decimal(10011101, Decimal).

Decimal = 157

yes

Verify the result:

| ?- Decimal is 0b10011101.

Decimal = 157

yes

推荐阅读