| It has been suggested that this page's contents be merged with the page Base Conversion. You can discuss this on the page's talk page. (February 2025) |
- For more information, see Binary number on Wikipedia.
This tutorial goes over the basics of converting numbers to/from binary.
Explanation
Binary is a base-2 numerical system that uses 2 digits: 0 and 1.
One use case in Scratch is packing together many boolean values for more efficient storage, especially useful for cloud variables which hold a limited number of digits. Booleans are binary, in that they can only be true or false.
In Scratch, what is often called a "binary number" is often a string consisting of of 0s and 1s.
Converting Numbers to Binary
In this example, note that the input number must be a non-zero positive integer.
to binary [19] // 19 in binary is 10011 define to binary (num) set [remainder v] to (num) set [binary v] to () // result is outputted to this variable as a string repeat until <(remainder) = [0]> set [binary v] to (join ((remainder) mod (2))(binary)) // join the binary digit to the result set [remainder v] to ([floor v] of ((remainder) / (2))) end
Padding Binary Numbers
It can be useful to insert zeroes to the start of a number so it has a fixed length. The script below will convert a binary number into a binary number of equal value, adding 0s.
pad binary number (10011) to length (8) // result is 00010011 define pad binary number (bin) to length (target length) set [binary v] to (bin) // result is outputted to this variable as a string repeat ((target length) - (length of (binary))) set [binary v] to (join (0)(binary)) end
Lookup Table
In some use cases a lookup table is a suitable way to implement a base conversion. In Scratch they are implemented with lists. This method is computationally more performant at the cost of memory (to store every possible result).
As a simple example, to convert to a 4-digit binary number you would need a list of 16 items like this: 0, 1, 10, ... 1110, 1111
(item ((6) + (1)) of [binary lookup v]) // 6 in binary is 110 (note that we add 1 because lists are 1-indexed)
One advantage with this method is that if zero padding is needed, the list can store binary numbers with zero padding already computed.
Converting Numbers From Binary
A binary number can be converted using the following:
((0) + (join [0b] (binary number)))
This script works because JavaScript (what Scratch is built on) interprets strings with "0b" at the beginning as binary.[1] Adding 0 to the string will convert the string into a number.
See Also
- Binary number on Wikipedia