lecture2

lecture2 - COMP 250 Winter 2010 lecture 2 binary...

This preview shows pages 1–2. Sign up to view the full content.

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 0 while m > 0 do b [ i ] m %2 m m/ 2 i i + 1 end while Example Convert 241 to binary. i m b[ ] 0 241 1 120 1 2 60 0 3 30 0 4 15 0 5 7 1 6 3 1 7 1 1 8 0 1 9 0 0 10 0 0 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.

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

What students are saying

• As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

Kiran Temple University Fox School of Business ‘17, Course Hero Intern

• I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

Dana University of Pennsylvania ‘17, Course Hero Intern

• The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

Jill Tulane University ‘16, Course Hero Intern