Page 1: Binary Conversion

Unit 8, Lab 2, Page 1

In this lab, you will extend your work with binary representation from Unit 4 to programming base conversion in Snap!.

On this page, you will explore a more elegant approach to base conversion.

In Unit 4 you learned about the binary representation of a number. In this project, you’ll 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:
decimal->binary (9827) reporting 10011001100011

To solve this problem, you’ll need to work with integer division into a quotient and remainder. For example, 17 ÷ 5 is 3 with a remainder of 2. Here’s how to find the quotient and remainder in Snap! :
(floor) of (17/5), reporting 3 (17)mod(5), reporting 2

The floor of a number is the largest integer less than or equal to that number. For example, the floor of 3.87 is 3. The floor function is in a block with other mathematical functions. In the palette, it looks like this: sqrt You’ll need to change the operation in the drop-down menu.

The mod block reports the remainder when the first input is divided by the second. You learned about mod on Unit 2 Lab 4 Page 1: The Mod Operator.

  1. Write the decimal->binary block.

    Need a hint?

    The biggest hint is that building the binary string should work from right to left, because the rightmost bit is always the ones column, while the leftmost bit’s value changes depending on how many digits the numeral has.

    Need more hints?

    Remember, the input to your block is a number, so you do arithmetic on it; the value reported by your block is a text string, so you need string operators (join) to make it.

    Need a bit more support?

    Try doing these calculations by hand, and look for connections. The connections may help you understand how to write your code.

    Talk with Your Partner

    • Explain why 13 is 1101 in binary.

    • Write 26 in binary. Write 27 in binary. How is each related to writing 13 in binary?

    • What are the quotient and remainder when you divide 27 by 2?

  1. “U8L2-Base-Conversion” Save your work as U8L2-Base-Conversion