ScriptLife

  • Learn AppleScript
  • About me
  • Archive
  • RSS
  • Ask me anything

Decimal to Binary Converter

This week I’ve started my computer science studies. Some of the exercises in one of the work books involved converting between decimal and binary numbers. Converting from binary to decimal is easy to do in the head, which I’ll show you, but I need pencil and paper to go the other way. I asked a teacher if he knew any tricks, and he challenged me to come up with an algorithm for it.

So here’s how you mentally convert from binary to decimal:

  • Read the binary number from left to right and start from the first number (always a 1).
  • Start your mental count, you begin with 1.
  • Move one digit to the right.
  • If it’s a zero, multiply your count by 2.
  • If it’s a one, multiply your count by 2 and add 1.
  • Repeat with all the digits and at the end your mental count will be the decimal value.

The AppleScript for converting decimal to binary is after the break.

set userNo to text returned of (display dialog "Enter a decimal number to convert" default answer "")
set binaryNo to ""
set powerList to {4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1} --if you need to convert larger numbers, just add more numbers to this list.
set decimalNo to userNo
repeat with thisPower in powerList
set binaryResult to getPowerRemainder(decimalNo, thisPower)
if item 1 of binaryResult is true then
set binaryNo to binaryNo & "1"
set decimalNo to item 2 of binaryResult
else
set binaryNo to binaryNo & "0"
set decimalNo to item 2 of binaryResult
end if
end repeat
display dialog (userNo as string) & " as decimal is" & return & return & text (offset of "1" in binaryNo) through end of binaryNo & " in binary"

on getPowerRemainder(inputNo, power)
if inputNo div power is 1 then
set remainder to inputNo mod power
return {true, remainder}
else
return {false, inputNo}
end if
end getPowerRemainder

    • #AppleScript
    • #Numbers
    • #Conversion
  • 1 year ago
  • 4
  • Comments
  • Permalink
  • Share
    Tweet

4 Notes/ Hide

  1. scriptlife posted this

Recent comments

Blog comments powered by Disqus
← Previous • Next →

Logo

About

The adventures of a scripter learning the trade. Currently I'm focused on AppleScript and Unix. I'm also learning Java and Cocoa / Objective-C but this blog is focused on scripting.
  • RSS
  • Random
  • Archive
  • Ask me anything
  • Mobile

Effector Theme by Carlo Franco.

Powered by Tumblr