This preview has intentionally blurred sections. Sign up to view the full version.View Full Document
Unformatted text preview: COMP 250 Winter 2010 lecture 2 – binary representations January 8, 2010 Converting from decimal to binary Last lecture I finished off by asking how to convert from decimal to binary. Here is the standard algorithm. It may not be obvious to you at first glance why this works (just as it was not obvious back in grade 4 why the addition and multiplication algorithms worked). But I’ll explain it below. Algorithm 1 Convert decimal to binary INPUT: a number m expressed in base 10 (decimal) OUTPUT: the number m expressed in base 2 using a bit array b [ ] i ← while m > do b [ i ] ← m %2 m ← m/ 2 i ← i + 1 end while Example Convert 241 to binary. i m b[ ] 241 1 120 1 2 60 3 30 4 15 5 7 1 6 3 1 7 1 1 8 1 9 10 11 : : and so the answer is 11110001. Note that there are an infinite number of 0’s on the left which you can truncate. Why does the algorithm work ? The first intuition comes from the observation that, when m is even, we can write it as m = 2 ∗ ( m/ 2) and, when m is odd, we can write it as m = 2( m/ 2) + 1, where the / operator ignores the remainder. Thus, for any positive integer m , m = 2( m/ 2) + ( m %2) where the / and % operators were as defined above. Let’s see why this observation makes the algorithm work....
View Full Document
This note was uploaded on 09/25/2011 for the course COMP 250 taught by Professor Blanchette during the Spring '08 term at McGill.
- Spring '08
- Computer Science