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:

whenclickedbroadcastnumbertobinarywhenIreceivenumbertobinarysetbitto0setbinarytoSetbinarytonothingaskInsertnumericalvalueandwaitsettemptoanswerrepeatuntiltemp=0setbittotempmod2Iftempisanoddnumber,theremainderoftemp/2isone,sothatspecificbitis1,otherwise,thatspecificbitis0setbinarytojoinbitbinaryBinaryreadsfromrighttoleft:...,16,8,4,2,1settemptoflooroftemp/2Dividethetempbytwoandrounddowntogetthenextbitendrepeatuntillengthofbinary>7Eachbytehas8bits.Ifthebinaryoutputstringisshorterthan8,thereneedtobezerosinfrontofitsothatithas8bitssetbinarytojoin0binaryendforeversaybinaryend

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

whenclickedbroadcastbinarytonumberwhenIreceivebinarytonumberaskInsertbinaryvalueandwaitsetito0setbinarytoSetbinarytonothingrepeatlengthofanswerchangeiby1ifnotletteriofanswer=0orletteriofanswer=1thenChecktomakesureitisbinaryforeversayInvalidinputendelsesetbinarytojoinbinaryletteriofanswerSetbinarytotheanswerendendsetbitto0setito0repeatlengthofbinarychangeiby1setbittobit*2+letteriofbinaryFunctiontoconvertbinarystringtonumberendforeverEx.1001=9;0*2+1=1;1*2+0=2;2*2+0=4;4*2+1=9;saybitend

Example Projects

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

See Also