r/AskProgramming • u/TorontoDude12344 • 21d ago
Algorithms Why is this the process to convert decimal to binary?
To convert a decimal number X to binary, you keep dividing X by 2, keeping the remainders in a list, until X is 0. Then you simply reverse the remainders list
void convert_N_to_binary(int n)
{
if (n != 0) {
pb(n / 2);
putchar('0' + n % 2);
}
}
I would like to understand the reasoning behind each step, Could someone break it down for me. Thank you
0
Upvotes
2
u/kilkil 20d ago
that's actually to do with the fundamental definition of bases. like from math.
like, if you took a number X, and kept dividing it by 10, keeping the remainders in a list, then reverse the list, that's how you convert X to base 10.
or if you divided it by 3, you would convert it to base 3.
basically when you write a number X in any base b, the first digit will always be "how many times can I fit b into X". the second digit will be "how many times can I fit b^2 into X". and so on.
the repeated division effectively simulates that: when you start with the first digit, you divide by the base once. when you reach the second digit, you already divided by the base once, so now you are effectively doing the equivalent of taking the original number, and dividing by the base squared. and so on.
8
u/MadocComadrin 21d ago edited 21d ago
The result of division with remainder doesn't change with the base. Keep that in mind, and imagine you have both the base 10 number and binary number side-by-side. When you divide by 2, you're cutting off the smallest bit with the remainder being exactly that bit. Essentially, you're grabbing the the least significant bit each time.
The list reversal at the end isn't necessary if you prepend the new bits to the list instead of adding them to the back.
E.g. 10 in binary is 1010. Doing the first step gets us 5 remainder 0. 5 is 101 in binary: we've cut off the last zero. Repeating that gets us 2 remainder 1. 2 is 10 in binary and we've cut off the last 1 to get there. The second to last step gets us 1 remainder 0, and the final division gets us 0 remainder 1. The remainders in order of seeing them was 0, 1, 0, and then 1, so if we reverse that (or kept track of them smartly) we get 1010, which is the 10 in base 10 we started with.
Edit: this also isn't the only process to do this. If you know/compute how big your number is in bits, you can start from the front instead (multiple ways).
4
u/saschaleib 21d ago
Don't forget that the computer already stores the number in binary and has to convert it to a decimal representation as string in order to display it for you. To convert a binary number directly to a string representation is much easier and faster to just probe the binary bits instead of (computationally expensive) divisions, i.e. just something like `
(v & (1 << n)) ? "1" : "0"`, or similar (just typed out of my head, not tested!) for the number of bits that the variable occupies.2
u/puppySaturation 21d ago
You can also think about what `convert_N_to_decimal` would look like. It would be the same, simply replace `/2` by `/10` and `% 2` with `% 10`. Does that one make sense? The algorithm is easily generalized to any number base, you only need to pick some symbols to use for digits larger than 9 (hexadecimal uses A, B, C, D, E, F).
2
u/This_Growth2898 21d ago
It works for any target numeral system. You're familiar with decimals, so let's do it for decimal target.
When you divide the number by 10, you get the remainder that is the last decimal digit, and the quotient that keeps the rest of the digits. Then you divide it once again, getting the next digit as remainder and so on. When you do it in decimal system, you just get to see the remainder and quotient of division by 10 immediately, but it is a universal law: the last digit is the remainder, and the rest of the number is the quotient.
Like, if the number is 123, you divide it by 10:
123/10 = 12 (rem. 3). 3 is the last digit.
12/10 = 1 (rem. 2) 2 is the next digit.
1/10 = 0 (rem 1). Since we got 0, this is the final step, and 1 is the first digit.
123 in decimal is 123.
The trick is that this process is independent from the numbering system. You can write it as well in binary or hexadecimals; values will be same.
And now the neat part: you don't have decimal numbers in your program. int is a binary number. printf converts it for you into decimal numbering system, but inside, it's binary.
2
u/who_you_are 21d ago
There are twos parts (which is also pretty explicit by the implementation).
Regardless of the counting system (binary (2), decimal (10), hex (16)) the system is the same - minus the value used to divide which match the system.
Let forget about binary, let use the base 10.
So you have 221. Since it is a 10 system you already can see, as a human, that there are 22x 10.
So 221 / 10 = 22. You have your left part.
Then the last part, you must "remove" the 22x 10. You could do 221 - 22x 10; or you can go straight for the modulo (which is about the same high level) to get the remaining. Modulo is the same operation done differently (and that can be optimized depending on the number).
As for the != 0 I'm a little bit confused. I don't know what the pb implementation is but I suspect it come from it or the if is otherwise useless. It is likely to assume both pb() and putchar() are outputting a value. I would have assumed they would always and as such the condition should have been >= 2 to call pb()
2
u/ern0plus4 21d ago
Use bitmask to get digits.
Start with mask=0x8000 for a 16-bit number, mask=0x80 for 8-bit. Perform AND on mask, if it's zero, the digit is 0, otherwise 1. Shift mask right and repeat until mask fades to zero.
1
u/mc_pm 21d ago
It's important to separate the actual numeric value (say 21) and the various ways you can *represent* that number. In decimal it's '21', in binary it's '10101', in hex it's '15', in octal it's '25', and in base-21 it's '10'. But they all refer to the same value. (Kind of like how an inch is 2.54 cm. The actual length you are measuring is the same, you're just getting that length back in different units. )
1
u/Recycled5000 21d ago edited 21d ago
You might start with a simpler or more correct code first.
The outer if statement means that given an input of zero, nothing at all will happen.
Given that there is no looping, the `pb` suggests recursion, but it is not defined in your snippet, and don’t see why it wouldn’t directly invoke itself instead.
Perhaps that “pb”means “print binary” and the function was renamed without renaming callers? As it is, this won’t compile, let alone run; you want it runnable so you can single step through it in a debugger for further understanding.
A common approach to converting a number to a string uses modulus arithmetic operation to peel the trailing digit off. If this is done repetitively and naively, the result will be a string that is the number backwards. So, using modulus, some approach to reversing the output digits is needed.
(There are other approaches that generate the string in forwards digits, but there is no mathematical operation to extract the first nonzero (ie most significant) digit, like there is to extract the (least significant) last digit. The algorithm has to find the position of the most significant digit, so this is arguably harder to compute.)
Assuming the code is corrected, recursion forms a loop. Because the recursion happens before the printing work, that printing is appended to whatever the recursive call prints. (Why does the recursion happen before the printing? Because of the ordering of the two statements in the body of the function. Reverse the recursive call and the print and it will print the digits backwards.)
The outer invocation of the function computes the trailing digit but the printing of it is delayed until the leading digits have been printed (via the recursive call)
This accomplishes the reversal of digits computed trailing to leading.
1
u/rupertavery64 21d ago edited 21d ago
When you write down a number in a certain base, each digit has a place value.
You are of course familiar with base 10 place values, as taught in school:
ones, tens, hundreds, thousands.
When you assemble a number in base 10, you get the digit's value and multiply it by the place value, then add those all together to get the whole number's value.
Now, it's important to remember that right now we are thinking and writing in base 10, because that's what we are familiar with, but think of the number's value as it's representation-free value, like a count of the number of fingers in your hand is "10", not the digits, but the concept, the value.
So for a number 1234 in base 10, this is equivalent to
Which is of course
You should also notice that each place value is base^n where n is the position of the number starting from 0 on the right
So
Can be rewritten as
So to extract the digits out of the number, we get the remainder of dividing the number by 10 using modulus division, then divide the number by 10 using integer divisin to "shift" the leftmost number out.
The numbers extracted in order are written from the right to the left: 1234
The result of integer division being 0 means that we've run out of numbers.
The thing is that this works for ANY base, just replace 10 with the base.
I'll use 123 here because it's shorter in binary:
The result: 1111011
or
Which is of course, 123
So you are taking a number (which remember, we're not talking about the decimal number digits, but the value itself) and splitting it up by powers of the base.
When you go into a base that has more than 10 digits, like hexadecimal, what do you do?
Each digit number is just a symbol, and that symbol represents a value. So we have 0-9, and then we just borrow some other symbols and have them represent numbers with higher values, like A-F.
When you think of numbers as just symbols, representing a value, it becomes a bit easier to understand. Like instead of the arabic numbers, you could represent them with other symbols, like base 4 as apple, orange, pear, grape.
The math behind it will still be the same.
1
u/cthulhu944 21d ago
N is the working number. As parts of the number are generated, n gets adjusted. The first line say if you have reached 0 then all the significant bits have been produced. It seems that the program is out of sequence. The putchar should be next. If you module the running value by 2 if it's 0, then the bit is 0, otherwise it's a 1. This gets output. Not sure what pb() does. The next statement should be an assignment to n as an integer division of the current value by 2. Note the this will output a binary that is ordered low to high. E.g. 4 would be 001 instead if the expected 100.
1
u/5a1vy 21d ago edited 21d ago
It's the Horner's scheme.
I will start by going through an example of converting via a greedy algorithm assuming you have no problems with it, e.g. convert 536 in base ten to base three: the biggest power of 3 still less then 536 is 3⁵, we can take it twice before exceeding 536, so the first digit is 2 and now we have to convert 536-3⁵=50 into base three, repeat until 0 is reached.
Now let's write our steps explicitly in one equation: 536=2×3⁵+0×3⁴+1×3³+2×3²+1×3¹+2×3⁰. Note that the validity of this equation doesn't depend on our representation of numbers, only on the numbers themselves, so what we can do is just rewrite both sides in base three (technically in any base, but we did all that to convert to base three, haven't we?), well, there's a problem with the left side, we don't know it in base three for now, but there aren't any problems with the right side, so let's focus on it for now. 0, 1 and 2 are just digits in base three, so they aren't a problem, 3 on the other hand we also know in base three — it's just 10, so the right side becomes 2×10⁵+0×10⁴+1×10³+2×10²+1×10¹+2×10⁰ in base three, and now it's clear that the answer is 201212 (all in base three). (Well, I hope it's clear, if not, feel free to ask me about this).
Now, with that established/remembered, let's rewrite our 2×3⁵+0×3⁴+1×3³+2×3²+1×3¹+2×3⁰ a bit, we can factor the common 3 out of the first one, two... five summands to get (2×3⁴+0×3³+1×3²+2×3¹+1)×3+2, and now look inside the parentheses, we again can factor a common 3 out of everything besides the last summand to get ((2×3³+0×3²+1×3¹+2)×3+1)×3+2, and again, and again... to get ((((2×3+0)×3+1)×3+2)×3+1)×3+2=536. Now look at the outmost part, it looks like (...)×3+2, which is precisely division by three with rest — some number times 3 plus the remainder. But look inside, it's the same thing inside the parentheses, and again, and then again still...
I think you get the picture, that's where it comes from, it's the same greedy algorithm just rewritten slightly differently. It's just in the greedy algorithm you go from "left to right" because you "first do all of the multiplications" and in this algorithm you go from "right to left" because you "try to do all additions first".
You can also technically rewrite all digits and the base in the target base and then simply evaluate the resulting expression. I mean, following my example, writing 536 as 5×10²+3×10¹+6 in base ten and then rewriting everything in base three, i.e. 12×101²+10×101¹+20 and then just evaluating everything in base three, which can also be done as is or with the Horner's scheme, it's just that here for some reason nobody feels like it's something different, unlike with the greedy algorithm or the one of your interest, even though it's the same thing.
It's easier, IMO, to understand all of it together and in a general case of arbitrary bases, so I would advise to try picking some numbers in arbitrary bases and with all of those methods convert them to some other arbitrary bases, e.g. 2543 (base seven) to base five with all four methods, 112102 (base three) to base eight with all four methods, and so on. Without the ability to do arithmetic without thinking you would be forced to check yourself on every step. After that, when you feel comfortable with integers, if you are feeling fancy, through some fractions into the mix (2501.0204 base seven to base nine, for example). After that... Well, it quickly becomes rather exotic.
1
u/timrprobocom 21d ago
Have you traced through it on paper? Be a human computer. It reveals many secrets.
1
u/tottasanorotta 19d ago edited 19d ago
Division by two is simply a right shift by 1 in binary and the remainder is the right most bit before the shift. So take the number 14, for example, which is 1110 in binary. We can already see what the remainders of each division will be. Those are exactly the bits starting from the right.
So a right shift is a division by two and a left shift is a multiplication by two. It's exactly the same as in decimal notation when you multiply or divide by 10. If you multiply 140 by ten then you left shift it by one with a 0 at the end and get 1400. And when you divide by ten you right shift it and get 14.
1
u/KillerCodeMonky 17d ago
This is a simple result of the definition of a number base:
abcdₙ
That is, the digits a, b, c, and d in base n, is equivalent to:
a×n³ + b×n² + c×n¹ + d×n⁰
The proposed conversion method is essentially breaking down the number into this second form, then assembling the resulting a, b, c, and d values into a single number.
1
u/Reasonable-Pay-8771 17d ago
Fundamental Theorem of Arithmetic. It's about how all positional numeric notation works. You divide by 2 over and over because the base of binary is 2. If you're converting to decimal, you use 10 instead.
1
u/Temporary_Pie2733 17d ago
It’s an example of Horner’s rule. Think of a binary number as polynomial in 2 rather than in x, with coefficients 0 and 1. Then we can rewrite 24 + 0(23) + 22 + 0(2) + 1, for example, as 1 + 2(0 + 2(1 + 2(1 + 2))).
1
u/FitMatch7966 16d ago
this isn't converting decimal anywhere. `n` is a binary number. You are just displaying it bit by bit