Madusanka
Madusanka

Reputation: 3018

How to convert decimal to binary number in prolog.?

dec_bin(1,1).
dec_bin(N,B):-N>1,X is N mod 2,Y is N//2,dec_bin(Y,B1),B=B1+X.

This gives me the output :

?- dec_bin(12,K).
K = 1+1+0+0.

But I want just 1100 without '+' symbol. Please someone help me..

Upvotes: 1

Views: 5971

Answers (1)

gusbro
gusbro

Reputation: 22585

I think what your are looking after is atom_concat/3. Also note that your procedure is failing on input number 0.

dec_bin(0,'0').
dec_bin(1,'1').
dec_bin(N,B):-N>1,X is N mod 2,Y is N//2,dec_bin(Y,B1),atom_concat(B1, X, B).

?- dec_bin(12,K). K = '1100'

Upvotes: 2

Related Questions