# Display the number of bits needed to represent a number

Challenge Level: Ready to expand

Learning outcomes

Students will be able to:

## Requirement:

Write a program that asks the user to enter a number of dots (i.e. decimal value) as the input and displays how many bits will be needed to represent that number as the output. For example, the number 15 can be represented in 4 bits, but 16 requires 5 bits. You can work this out by starting with the number 1, and doubling it until it gives you a value more than the number you need to represent, so this program can be based on the earlier challenge to work out the number of dots on each card.

## Testing examples:

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

Input Output
5 3 bits
31 5 bits
32 6 bits
1 1 bits

## 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
when green flag clicked

ask [Please enter the number of dots:] and wait

change [bits v] by (1)

repeat until <(total number of dots) < (bit value)>
end

say (join (join (join [You will need ] (bits)) [ bits to store number ]) (total number of dots))
set [total number of dots v] to (answer)

set [bits v] to [0]

set [bit value v] to [1]

set [bit value v] to ((bit value) * (2))
Hints
• Make variables called:

• "total number of dots" and set its value to the number entered by the end user.
• “bit value” and set its value to ‘1’. Double its value until it is bigger than the “total number of dots”.
• “bits” and set its value to 0. Every time that you double the “bit value” you need to add a new bit for storing the number (increase the value of “bits” by 1).
• Use repeat until <> block to repeat the blocks until “total number of dots” is greater than the “bit value”. Stop the loop when you find the “bit value” which is larger than the “total number of dots”. Display the value of “bits” as the output.

• Set the variable “bit value” to ‘1’ and double it (Use the  () * () operation under “Operators” to multiply the “bit value” by 2) until it is bigger than the “total number of dots”. Every time that you double the “bit value” you need to add a new bit for storing the number. You can do this by using the change [] by () block to increase the value of variable “bits” value by 1. Use repeat until <> block to repeat these steps until condition is true. In this challenge you need to repeat the blocks until “total number of dots” is greater than the “bit value”. Stop the loop when you find the “bit value” is larger than the “total number of dots”.

• Test your program with some values on the boundaries (for example number 31 would need 5 bits and 32 needs 6 bits).

Python

Block-based