HiveBrain v1.2.0
Get Started
← Back to all entries
snippetMinor

Algorithm to convert decimal number to binary

Submitted by: @import:stackexchange-cs··
0
Viewed 0 times
numberconvertdecimalalgorithmbinary

Problem

I am reading this material to understand the basics of number system.
I am stuck at a point in that material where it writes the algorithm to convert a decimal number to binary number.
The heading of that part where I am stuck is Decimal to Base
The algorithm (may be presented less than faithfully, please refer the link) it mentions there is:



  • Let $p = \lfloor \sqrt{V} \rfloor$



  • Let $v = \lfloor \dfrac V {B^p} \rfloor$



(v is the next digit to the right)

  • Make $V = V − v * B^p$



  • Repeat steps 1 through 3 until $p = 0$




It is explaining by taking an example of converting decimal number 236 to binary.

I am not getting how it is calculating the 1st step, i.e. to get the value of p.

It writes that p = int(square root of V)

Now, square root of 236 = 15.36229149573721635154

As per point number 1, p = integer part of 15.36229149573721635154
So, I remove the decimal part and p then becomes 15. But the material there says it is 7.

I can't get what is happening here. I am stuck.

Solution

Just converting the comment into a short answer:

$7 = \text{int}(\log_{2} 236)$. Generally, $p = \text{int}(\log_{B}V)$.

As other people pointed out, this algorithm is needlessly complicated and not practical; it is not easy to calculate $\log_B V$ for large $V$ by pencil and paper. Instead, use the other algorithm which is also mentioned in the article you are reading:

From decimal to binary

  • Step 1: Check if your number is odd or even.



  • Step 2: If it's even, write 0 (proceeding backwards, adding binary digits to the left of the result).



  • Step 3: Otherwise, if it's odd, write 1 (in the same way).



  • Step 4: Divide your number by 2 (dropping any fraction) and go back to step 1. Repeat until your original number is 0.

Context

StackExchange Computer Science Q#51789, answer score: 5

Revisions (0)

No revisions yet.