2
$\begingroup$

With the following code I produce the binary digits of n=13:

n=13;

Q = Quotient[n, 2]; 

While[Q != 0, Print[Mod[n, 2]]; Q = Quotient[n, 2]; n = Q]

The problem is that it outputs the digits as

1

0

1

1

but I want them to appear horizontally 1101. What is the most direct way to produce the desired effect regarding the output's style?

$\endgroup$
1

4 Answers 4

5
$\begingroup$

Updated to reverse the result of OP's loop

This makes a list (which needs to be reversed):

Q = Quotient[n, 2];
result = {};
While[Q != 0, AppendTo[result, Mod[n, 2]]; Q = Quotient[n, 2]; n = Q]

Reverse[result]

{1, 1, 0, 1}

If you want a string:

StringJoin[ToString /@ Reverse[result]]

"1101"

There's also

BaseForm[13, 2]

enter image description here

IntegerString[13, 2]

"1101"

$\endgroup$
0
3
$\begingroup$

How about

BaseForm[13,2]

or more generally

BaseForm[n,base]
$\endgroup$
3
$\begingroup$

What is the most direct way to produce the desired effect?

Do not use Print. I am sure there are at least 10 ways to do this, one way could be to replace Print by Sow and keeping your main logic as is. But this can also be done with explicit loop

doit[n_Integer?Positive]:=Module[{m=n,q},
   q=Quotient[m,2];
   While[q!=0,
     Sow[Mod[m,2]];
     q=Quotient[m,2];
     m=q
  ]
]

And now do

r = First@Last@Reap@doit[13];
StringJoin[ToString /@ Reverse[r]]
ToExpression[%]

Mathematica graphics

$\endgroup$
2
$\begingroup$

"What is the most direct way to produce the desired effect?"

BaseForm[13, 2]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.