Q&A

# A formal-logic formula for decimal to binary conversion

+0
−0

How can one calculate that decimal 2 is binary 10 or that decimal 10 is binary 1010?

Instead of memorizing decimal to binary conversion tables, what formal-logic formula can one use to do generally any decimal to binary calculation?

Why does this post require moderator attention?
Why should this post be closed?

You are accessing this answer with a direct link, so it's being shown above all other answers regardless of its score. You can return to the normal view.

+2
−0

If you have a non-negative integer $n$, and the base $b$ representation of $n$ is a sequence of digits, numbered from the right as $d_k\dots d_2d_1d_0$, then $d_i = \left\lfloor \frac{n}{b^i} \right\rfloor \bmod b$.

For example, decimal 10 is binary 1010 because:

$$d_3 = \left\lfloor \frac{10}{2^3} \right\rfloor \bmod 2 = 1 \bmod 2 = 1$$ $$d_2 = \left\lfloor \frac{10}{2^2} \right\rfloor \bmod 2 = 2 \bmod 2 = 0$$ $$d_1 = \left\lfloor \frac{10}{2^1} \right\rfloor \bmod 2 = 5 \bmod 2 = 1$$ $$d_0 = \left\lfloor \frac{10}{2^0} \right\rfloor \bmod 2 = 10 \bmod 2 = 0$$

(For all $i > 3$, $d_i = 0$, because $10 < 2^i$.)

This can be computed more efficiently using a loop or recursion, but this is the more succinct mathematical description.

By the way, extending this formula to non-integers is straightforward—just continue the digit numbering past the point as $d_k\dots d_2d_1d_0.d_{-1}d_{-2}\dots$, and the formula is still valid, modulo the usual philosophical concerns about infinite sequences of digits.

Why does this post require moderator attention?

+2
−0

The formal formula for base conversion of a non-negative number is $$x = \left\lfloor \frac{x}{b} \right\rfloor b + (x \bmod b)$$ For binary, $b=2$.

Why does this post require moderator attention?

+0
−0

I am giving Python code.

# Function to convert decimal number
# to binary using recursion
def DecimalToBinary(num):

if num >= 1:
DecimalToBinary(num // 2)
print(num % 2, end = '')

# Driver Code
if __name__ == '__main__':

# decimal value
dec_val = 24

# Calling function
DecimalToBinary(dec_val) I hope it is understandable. Keep diving until you get zero. And, note every remainders. Remainders is binary.

Note : sometime some computers use 0 before binary. E.g. binary of 85 is 1010101 but, some computer will write 01010101.

I think it happens for encoding. Any computer can decode both and, return same value.

Why does this post require moderator attention? 