Binary Conversion

Материал из Поле цифровой дидактики

This tutorial goes over the basics of converting numbers into binary.

Explanation

Binary is a base-2 numerical system that only uses two characters: 0 and 1

Using binary in Scratch projects allows for very simple encoding and decoding of values. Because cloud variables can only use numbers, converting strings into binary can allow for more advanced cloud storage.

Converting Numbers to Binary

This program requires one sprite and four variables. The following variables are required:

  • (binary)
  • (bit)
  • (i)
  • (temp)

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

when green flag clicked
broadcast (number to binary v)

when I receive [number to binary v]
set [bit v] to [0]
set [binary v] to [] // Set binary to nothing
ask [Insert numerical value] and wait
set [temp v] to (answer)
repeat until <(temp) = [0]>
set [bit v] to ((temp) mod [2]) // If temp is an odd number, the remainder of temp / 2 is one, so that specific bit is 1, otherwise, that specific bit is 0
set [binary v] to (join (bit)(binary)) // Binary reads from right to left: ..., 16, 8, 4, 2, 1
set [temp v] to ([floor v] of ((temp) / (2))) // Divide the temp by two and round down to get the next bit
end
repeat until <(length of (binary)) > [7]> // Each byte has 8 bits. If the binary output string is shorter than 8, there need to be zeros in front of it so that it has 8 bits
set [binary v] to (join [0](binary))
end
forever
say (binary)
end

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

when green flag clicked
broadcast (binary to number v)

when I receive [binary to number v]
ask [Insert binary value] and wait
set [i v] to [0]
set [binary v] to [] // Set binary to nothing
repeat (length of (answer))
change [i v] by [1]
if <not<<(letter (i) of (answer)) = [0]> or <(letter (i) of (answer)) = [1]>>> then // Check to make sure it is binary
forever
say [Invalid input]
end
else
set [binary v] to (join (binary)(letter (i) of (answer))) // Set binary to the answer
end
end
set [bit v] to [0]
set [i v] to [0]
repeat (length of (binary))
change [i v] by [1]
set [bit v] to (((bit) * [2]) + (letter (i) of (binary))) // Function to convert binary string to number
end
forever  // Ex. 1001 = 9; 0*2 + 1 = 1; 1*2 + 0 = 2; 2*2 + 0 = 4; 4*2 + 1 = 9;
say (bit)
end

Example Projects

The following is an example project that converts numbers to binary and back:

See Also