I'm currently building a binary translator (binary to text) in the AppleScript editor. The code I wrote only lets you input one binary number at a time. I want to enter in multiple binary numbers at a time and still have the code translate it. I've been thinking of lots of different ways to have the code translate multiple numbers (binary), but everything I try doesn't seem to work. I'm relatively new to AppleScript, and I'm pretty stumped. Here's the code:
set binaryString to text returned of (display dialog "Binary Goes Here:" default answer "" with icon note buttons {"Cancel", "Translator"} default button 2 with title "Binary Translator") as string
set n8 to character 1 of binaryString
set n7 to character 2 of binaryString
set n6 to character 3 of binaryString
set n5 to character 4 of binaryString
set n4 to character 5 of binaryString
set n3 to character 6 of binaryString
set n2 to character 7 of binaryString
set n1 to character 8 of binaryString
if n8 = "0" then
set d8 to 0
else if n8 = "1" then
set d8 to 128
end if
if n7 = "0" then
set d7 to 0
else if n7 = "1" then
set d7 to 64
end if
if n6 = "0" then
set d6 to 0
else if n6 = "1" then
set d6 to 32
end if
if n5 = "0" then
set d5 to 0
else if n5 = "1" then
set d5 to 16
end if
if n4 = "0" then
set d4 to 0
else if n4 = "1" then
set d4 to 8
end if
if n3 = "0" then
set d3 to 0
else if n3 = "1" then
set d3 to 4
end if
if n2 = "0" then
set d2 to 0
else if n2 = "1" then
set d2 to 2
end if
if n1 = "0" then
set d1 to 0
else if n1 = "1" then
set d1 to 1
end if
set decimalString to (d1 + d2 + d3 + d4 + d5 + d6 + d7 + d8)
set asciiString to (ASCII character (decimalString))
return asciiString
Best Answer
Your script can be heavily simplified. What it looks like you're doing is converting a binary number into base 10 (denary), and then from there into a character code. (Side-note: It's always helpful to try and be explicit in describing what your code does--or is intending to do.)
You wish to repeat this process multiple times to convert as many binary numbers as the user supplies. There aren't a great many options for easily allowing multiple values to be obtained from a user. But it looks like you're experimenting with binary/text encoding of data, and that these binary numbers likely represent 8 bits of a single byte of data, therefore it seems reasonable to let a user supply as many bytes of data he wishes in a single input dialog, simply separating each binary value by a space, e.g.
which would represent three bytes of data in binary form that are easy to split into individual items and converted one-by-one.
To this end, it makes sense to put the chunk of code that does the base conversion inside a
handler
(function) that can be re-used again and again to perform as many conversions as one needs without having to write out identical code again and again.Here's a draft of a script that does all of this: