I was trying this binary to decimal conversion test for practice.
decimal to binary conversion
variable counts
: db-test ( n1 -- b1 b2 b3 b4 ... )
0 counts !
begin
dup
while
2 /mod swap >r
1 counts +!
repeat
counts 0 do r> loop
;
The above code works but the binary digits are in reverse order (13 is 1101):
13 db-test ok
.s <5> 1 0 1 1 0 ok
In order to reverse the stack I thought of placing the remainders in the return stack.
When I take out the commented lines
variable counts
: db-test ( n1 -- b1 b2 b3 b4 ... )
0 counts !
begin
dup
while
2 /mod swap >r
1 counts +!
repeat
counts 0 do r> loop
;
I get this:
13 db-test ok
.s <5> 0 0 4517901033 2 2 ok
It looks like the loop in the last line is not getting back the remainders I sent to the return stack. And why do I see memory location instead of the value?
What am I doing wrong?