**For more information, see Binary number on Wikipedia.**
This tutorial goes over the basics of **converting numbers into binary**.

## Explanation

Binary is a base-2 numerical system that uses 2 digits; `0`

and `1`

.

Using binary in Scratch projects allows for very simple encoding and decoding of values. Because cloud variables hold a limited amount of digits, converting a list of true / false values from binary to decimal will make use of the limited storage more efficiently.

## Converting Numbers to Binary

Note that the numbers must be a non-negative positive integer.

This program requires two variables. The following variables are required:

`(binary)`

`(i)`

Once these variables have been created, the script below should be added to convert a number to binary:

define number to binary (num) set [i v] to (num) set [binary v] to () repeat until <(i) = (0)> set [binary v] to (join ((i) mod (2))(binary)) set [i v] to ([floor v] of ((i) / (2))) end

Likewise, the script below should be added to convert binary to numbers:

((0) + (join [0b] (binary)))

This script works because JavaScript (what Scratch is built on) interprets numbers with "0b" at the beginning as binary.^{[1]} Adding 0 to the string will convert the string into a number.

### Padding Binary Numbers

The script below will convert a binary number into a binary number of equal value, adding 0's at the beginning so that the number has a multiple of 8 digits.

Example:

`101 -> 00000101`

`11101 -> 00011101`

`11101110 -> 11101110`

`101101101 -> 0000000101101101`

`1101101101110 -> 0001101101101110`

Script:

define pad binary number to have a multiple of 8 digits (bin) set [binary v] to (bin) repeat until <((length of (binary)) mod (8)) = (0)> set [binary v] to (join (0)(binary))

## See Also

- Binary number on Wikipedia