The question is: do you know how to do it "by hand"? Here's my process (the number that you want to convert is n):
- Find the largest k such that 2k ≤ n. Your binary number k+1 digits, starting with a 1
- Subtract 2k from your n.
- Subtract 1 from k.
- If 2k is larger than n, put a 0 down in your binary number. If k is smaller or equal to n, place a 1 in your binary number, and subtract 2k from n.
- redo the previous step until k is 0.
Now, here's a simple example for n=10:
- 20 = 1 ≤ 10,
21 = 2 ≤ 10,
22 = 4 ≤ 10,
23 = 8 ≤ 10,
24 = 16 > 10.
Thus, k=3, and our binary digit will have 4 bits, starting with a 1.
- n=10-23=2,
k=3-1=2
- 22 = 4 > 2, so we put a 0.
k=2-1=1
- 21 = 2 ≤ 2, so we put a 1.
k=1-1=0,
n=2-21=0
- 20 = 1 > 0, so we put a 0.
- So, our net result is 1010
From this, you should be able to code your algorithm. A
for loop comes to mind...;)
thor