If you study the examples presented here, you will notice that method 2 (Descending Powers of Two and Subtraction) is in tandem with a video you may have watched earlier so it is recommended that you try this method first to code Get Binary Digits
. The algorithm goes something like this:
Starting with the largest power of 2 down to the lowest power of 2 (in our case from 27 to 20 as there are 8 binary digits) check if that power of 2 is contained in the number (i.e. if the number is greater than or equal to that power of 2.) If so, write 1 for the current binary digit and replace the number with that power of 2 subtracted from the number. Otherwise, write 0 for the current binary digit.
Note: In the starter file, if you look at the Operators menu you will notice that a blockIf you decide to code Get Binary Digits
with method 1 (Short Division by Two with Remainder), then you will need to compute a lot of remainders and quotients during division with 2, which you can get by using the mod
and floor
operators in Snap!. The code will be similar to the Get Decimal Digits
code.
Get Binary Digits
is to fill the Binary Digits List with the correct sequence of zeros and ones, padding the front of the list with zeros if necessary. The rest of the program will take care of the proper display of these digits.