1

This is what I tried to convert Octal number to binary. What I wanted to do was to find the remainder of the given octal number when divided by 10 to get each digit and convert that digit to 3 bit binary. But this code is not producing any output. Please help on this. Thanks in advance.

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

convert_oct(N, O) :-
    X is N mod 10,
    convert_bin(X, B),
    Y is N // 10,
    convert_oct(Y, O1),
    atom_concat(O1, B, O).
repeat
  • 18,496
  • 4
  • 54
  • 166
  • 2
    off topic: N is octal, must use 8 as base, not 10 – CapelliC Dec 06 '15 at 08:11
  • I am very well aware of that. But to convert octal to binary, you just convert each of the digits to binary number of 3 bits. Example octal number 123 is 001010011. So to do this 123 mod 10 gives 3. And binary of 3 is 011. And then 123/10 is 12. 12 mod 10 is 2 and binary of 2 is 010. Lastly 12/10 is 1 and 1 mod 10 is 1 and it's binary is 001. And clearly that's what I did in this code which you might have missed to understand. – eagertolearn Dec 06 '15 at 09:25
  • 2
    Your inconsistent representations have added to the confusion. You are treating what is, in fact, a decimal number, as understood by Prolog, as if it were octal, but then your output is an atom representing binary rather than using decimal number to represent the binary as you did with the octal input. Regardless, one issue I see is you have no base case for `convert_oct/2`. At least if you do, you haven't shown it. Without a base case, it's bound to just fail without a result. – lurker Dec 06 '15 at 12:53
  • I am new to prolog.. Can you let me know how I can make the code work in this case? Just adding a base case for convert_oct will give me right results? – eagertolearn Dec 06 '15 at 16:14
  • Why not add a good base case and find out? :) Look at your `convert_oct/2` predicate and figure out how the recursion will come to an end. Under what conditions would that be so? – lurker Dec 07 '15 at 11:40

1 Answers1

2

The encoded number should better be a list of digits—not an atom!

Using and n_base_digits/3 we can write the following sample queries:

?- use_module(library(clpfd)).
true.

?- n_base_digits(27, 2, Binary).
Binary = [1,1,0,1,1].

?- n_base_digits(N, 2, [1,1,0,0,1,0,0,1]).
   N = 201
;  false.

?- n_base_digits(N, 2, [1,1,0,0,1,0,0,1]),
   n_base_digits(N, 8, Octal).
   N = 201, Octal = [3,1,1]
;  false.
Community
  • 1
  • 1
repeat
  • 18,496
  • 4
  • 54
  • 166