Re: Binary => decimal conversion
Re: Binary => decimal conversion
- Subject: Re: Binary => decimal conversion
- From: Nigel Garvey <email@hidden>
- Date: Sat, 25 Nov 2000 10:51:50 +0000
Paul Berkowitz wrote on Fri, 24 Nov 2000 18:53:47 -0800:
>
On 11/24/00 5:16 PM, "John Welch" <email@hidden> wrote:
>
>
> Is there an OSAX out there that does decimal to binary conversion and vice
>
> versa?
>
>
>
>
I haven't found an osax, but I've written two handlers. They presuppose that
>
the binary and decimal numbers are presented as "integers" to AppleScript.
>
Just modify the first line of either to "string" if presented as strings.
>
>
to Binarize(dec)
>
if class of dec is integer then
>
set bin to ""
>
set x to dec
>
repeat until x < 1
>
set y to x mod 2
>
set x to x div 2
>
set bin to "" & y & bin
>
end repeat
>
return (bin as integer)
>
end if
>
end Binarize
[...]
>
Binarize(71)
>
-- 1000111
Binarize(71) div 2
--> 500055
You can only represent a number in binary form as a string. Otherwise
these handlers are very effective.
Earlier this year, I wrote a more involved integer-to-binary-string
routine for alt.comp.lang.applescript. It handles both positive and
negative integers and arranges the output's digits in groups of eight,
subdivided into fours. I haven't looked at it since, so it may be
possible to optimise it a bit. (No pun intended!):
on doBinary(n)
if the class of n is not integer then ,
return (n as string) & " is not an integer!"
if n < 0 then -- negative number
-- convert to a suitable two's complement
set p to 2
repeat until p > -n
set p to p * 2
end repeat
set n to p * 2 + n
set thePadding to "11111111"
else -- positive number
set thePadding to "00000000"
end if
-- Work out the basic binary string
set theBin to ""
repeat until n = 0
set theBin to ((n mod 2) as string) & theBin
set n to n div 2
end repeat
-- Add the leading ones or zeros
set theCut to ((((length of theBin) - 1) div 8) + 1) * 8
set thePaddedBin to text -theCut thru -1 of (thePadding & theBin)
-- Insert the space separators
set theBin to ""
repeat with i from 1 to the (length of thePaddedBin) - 3 by 4
set theBin to theBin & text i thru (i + 3) of thePaddedBin & space
end repeat
set theBin to text 1 thru -2 of theBin -- drop the trailing space
return theBin
end doBinary
doBinary(71)
--> "0100 0111"
doBinary(-71)
--> "1011 1001"
doBinary(256)
--> "0000 0001 0000 0000"
NG