MACSCRPT Archives

May 2003

MACSCRPT@LISTSERV.DARTMOUTH.EDU

Options: Use Monospaced Font
Show Text Part by Default
Show All Mail Headers

Message: [<< First] [< Prev] [Next >] [Last >>]
Topic: [<< First] [< Prev] [Next >] [Last >>]
Author: [<< First] [< Prev] [Next >] [Last >>]

Print Reply
Subject:
From:
Nigel Garvey <[log in to unmask]>
Reply To:
Macintosh Scripting Systems <[log in to unmask]>
Date:
Fri, 2 May 2003 22:18:45 +0100
Content-Type:
text/plain
Parts/Attachments:
text/plain (76 lines)
"Pelto, Chuck" wrote on Wed, 30 Apr 2003 08:04:22 -0600:

>Does anyone have an algorthym for deriving a hexidecimal number in
>AppleScript?

I thought I'd have a go at this myself. :-) Fractional numbers are
rounded to the nearest whole-number value, but otherwise there are no
input checks here:

-- n: input number, decimal or "scientific notation" string
-- res: "resolution" - factor of the number of digits in the output string

on hexStr(n, res)
  -- Round n to the nearest whole-number
  set n to n div 0.5 - n div 1

  -- Get the value which, in hexadecimal notation, is 1 followed by 'res'
zeros
  set resVal to 16 ^ res
  -- Get the value of the lowest power of this that is larger than (ABS
n). It
  -- will be added to n to make a value which, in hexadecimal, is "1"
followed
  -- by n's digits. The "1" is a dummy to generate leading zeros where
necessary
  -- and will be omitted from the output string.
  set powerVal to resVal
  if n < 0 then
    set nAbs to 0 - n
  else
    set nAbs to n
  end if
  repeat until powerVal > nAbs
    set powerVal to powerVal * resVal
  end repeat
  -- If n is negative, make adjustments to the power value before adding
them
  if n < 0 then
    -- If (ABS n) is more than half the power value, the hexadecimal
digit after
    -- the dummy "1" will turn out to be positive. Go up one more power,
which
    -- will cause the right number of leading "F"'s to be introduced.
    if nAbs > powerVal div 2 then set powerVal to powerVal * resVal
    -- Adding the negative n to powerVal will "borrow" the leading, dummy
"1".
    -- Make it a "2" so that there's still "1" there afterwards.
    set powerVal to powerVal + powerVal
  end if
  -- Finally add n and the power value
  set nTemp to powerVal + n

  -- Initialise the hexadecimal string with the lowest-order digit
  set hexDigits to "0123456789ABCDEF"
  set hexOut to character (nTemp mod 16 + 1) of hexDigits
  -- Successively prepend the remaining digits, except for the initial "1"
  set nTemp to nTemp div 16
  repeat until nTemp = 1
    set hexOut to character (nTemp mod 16 + 1) of hexDigits & hexOut
    set nTemp to nTemp div 16
  end repeat

  return hexOut
end hexStr

hexStr(-255, 1) -- multiple of 1 digits
--> "F01"

hexStr(-255, 2) -- multiple of 2 digits
--> "FF01"

hexStr(1.23456789E+9, 4)
--> "499602D2"

NG

ATOM RSS1 RSS2