Convert a positive decimal number to a binary number

Challenge Level: Ready to expand

Learning outcomes

Students will be able to:

Requirement:

Write a program that asks the user to enter any decimal number as the input and displays the binary cards representing that number using '1' for dots showing and '0' for not showing as the output (this converts the decimal number to binary). Do this by working out the largest bit value needed, and then working down through smaller bit values.

Testing examples:

Your program should display the outputs shown in this table for the given inputs provided:

Input Output
31 The binary representation for the number 31 is 11111
32 The binary representation for the number 32 is 100000
1 The binary representation for the number 1 is 1

Languages

Scratch

What it should look like

Click on the green flag, enter the inputs provided in the “testing examples” to see the expected output of your program.

Recommended blocks
whenclickedaskPlease enter a decimal number:andwaitsayjoinjoinjoinThe binary representation for the number answer is binarynumber
ifdecimalnumber>bitvalueordecimalnumber=bitvaluethenelserepeatuntildecimalnumber<bitvaluerepeatuntilbitvalue=1
setdecimal numbertoanswersetbit valueto1setbinary numbertosetbit valuetobitvalue*2setbit valuetobitvalue/2setbinary numbertojoinbinarynumber1setdecimal numbertodecimalnumber-bitvaluesetbinary numbertojoinbinarynumber0
Hints
  • Make variables called:

    • “decimal number” and set its value to the input number given by the end user.
    • “bit value” and set its value to ‘1’. Find the smallest bit value which is larger than the “decimal number” by doubling value of “bit value” until it is bigger than the “decimal number”.
    • “binary number” is a string variable and stores the binary cards needed (‘1’ for dots showing and ‘0’ for not showing).
  • Set the variable “bit value” to 1 and find the smallest “bit value” which is larger than “decimal number” by multiplying “bit value” by 2 (Use the * block under “Operators” to multiply the “bit value” by 2) until it is larger than “decimal number”. You can do this by using a repeatuntil loop.

  • Now divide the “bit value” by 2 and check if “decimal number” is greater than or equal to “bit value”. If it is, add ‘1’ to string variable “cards” and subtract “bit value” from the “ decimal number”. If not, add ‘0’ to string variable “cards”. Repeat until “bit value” is equal to 1. Display the value of “cards” as the output.

Show Scratch solution

Python