If there's one thing everyone knows about computers, it's that they think in zeros and ones. As you know by now, the whole point of computer science is abstraction, so that you can program and use computers without ever having to deal with their low-level circuitry. Still, for some reason the people who made up the AP curriculum standards think you should know about binary.
People usually say "binary numbers," but the mathematicians on our team won't let us do that. Numbers are numbers, regardless of how they're represented: "XVIII" and "18" represent the same number, and so, as you'll see, does "10010" in binary.
In plain old decimal (base 10) notation, each digit's position represents a power of 10, starting with 1 (which is 100) on the right, and multiplying by 10 as you move left. So, for example, 9827 is, from right to left,
9 × 103 + 8 × 102 + 2 × 101 + 7 × 100
(Why right to left? Because the rightmost digit is always multiplied by 100, but in a long number such as 432786149314152718281828459045 you can't tell what power of 10 to multiply the leftmost digit by, until you count up to it from the right.)
Binary uses the same positional idea, but with powers of two instead of powers of ten. So 10010 binary represents, from right to left,
1 * 24 + 0 × 23 + 0 × 22 + 1 × 21 + 0 × 20 = 2 + 16 = 18 decimal
(Snap! blurs the distinction between a number and a string of digits, allowing you to use text operators on numbers and arithmetic operators on strings of digits. But for right now, don't do that; it'll be less confusing if you do arithmetic on the input, but combine the digits of the reported result using join
.)
Our goal is to write a reporter decimal->binary
that takes a number (which Snap! represents in decimal) as input, and reports a string of zeros and ones that represent the same number in binary:
To solve this problem, you're going to have to know how to do integer division the way you did it in third grade, before you knew about fractions: 17 รท 5 is 3 remainder 2. Here's how to do that in Snap! :
In the Operators palette there's a block sqrt of
in which the word sqrt
is part of a menu of mathematical operations. From that menu, choose floor
to get the integer part of the quotient. (It's called "floor" because it's the nearest integer smaller than its input, as opposed to round
, which finds the nearest integer whether smaller or larger.) "Mod" is short for modulo, which is the fancy mathematical name for remainder.
decimal->binary
before reading the next page.