Anyone know the simplest way to convert binary to decimal and backforth?
python - Converting binary to decimal integer output - Stack Overflow
Homework Help: Converting Decimal to Binary?
How would I convert a long decimal to binary without using a calculator? - Mathematics Stack Exchange
Videos
I have seen the udemy course on binary to decimal and decimal to binary but it's kinda hard for certain numbers such as 127, 125.
I'm learning subnetting and for me understanding binary is really imp. Pls help.
You can use int and set the base to 2 (for binary):
>>> binary = raw_input('enter a number: ')
enter a number: 11001
>>> int(binary, 2)
25
>>>
However, if you cannot use int like that, then you could always do this:
binary = raw_input('enter a number: ')
decimal = 0
for digit in binary:
decimal = decimal*2 + int(digit)
print decimal
Below is a demonstration:
>>> binary = raw_input('enter a number: ')
enter a number: 11001
>>> decimal = 0
>>> for digit in binary:
... decimal = decimal*2 + int(digit)
...
>>> print decimal
25
>>>
Binary to Decimal
int(binaryString, 2)
Decimal to Binary
format(decimal ,"b")
ps: I understand that the author doesn't want a built-in function. But this question comes up on the google feed even for those who are okay with in-built function.
I didn't know where to post a question like this, so I am posting it here.
I have been told to find out how to convert to Binary and was given the number 47.
Everywhere I have looked has been confusing, so I am asking: How would I convert 47 into binary?
To expand on my comment: Let's say we want to convert $409$ to binary. We first need to know how many bits we'll need; we need to know the largest power of $2$ that's less than $409$. We'll also need all smaller powers of $2$, so let's write those down (they are all very easy to calculate by hand).
\begin{array}{c|c|c|c|c|c} k & 8 & 7 & 6 & 5 & 4 & 3 & 2 & 1 & 0 \\\hline 2^k &256 & 128 & 64 & 32 & 16 & 8 & 4 & 2 & 1 \end{array}
So we'll need $9$ bits. To find them, we essentially subtract the largest power of $2$ from our remainders, repeatedly (for example, $409 - 256 = 153$): \begin{align*} 409 &= 256\cdot 1 + 153 \\ 153 &= 128 \cdot 1 + 25 \\ 25 &= 16 \cdot 1 + 9 \\ 9 &= 8 \cdot 1 + 1 \\ 1 &= 1 \cdot 1 \end{align*}
Since we saw $256,\ 128,\ 16,\ 8,$ and $1$ show up in the process, we have $$409_{10} = 110011001_2.$$
Of course, for a number like yours, we would need many more powers of $2$, in general.
But! It just so happens that $2147483647 = 2^{31} - 1$, and its binary representation is literally $$2147483647_{10} = \underbrace{111\ldots 1_2}_{31\text{ times}}$$ (try smaller numbers that are one less than a power of $2$, like $7, 15, 31$, and you'll see the pattern).
You can convert to a different power-of-two base, e.g. octal or hexadecimal, first. That's $3$ or $4$ times fewer divisions, and then you can very quickly convert to binary using a lookup table for the octal or hexadecimal digits.