on numToHex(n, res) -- Round the input value to the nearest whole-number. (Just in case it's fractional.) set n to n div 0.5 - n div 1 script o property hexDigits : missing value property hexOut : {} end script if (n > -1) then -- The number's positive. set o's hexDigits to {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"} -- Construct a list of the hexadecimal digits, working backwards from the lowest-order one. set widthNow to 0 repeat set beginning of o's hexOut to item (n mod 16 + 1) of o's hexDigits set n to n div 16 set widthNow to widthNow + 1 -- Finish when n is exhausted and the digit count is a multiple of the resolution. if (n is 0) and (widthNow mod res is 0) then exit repeat end repeat else -- The number's negative. set o's hexDigits to {"1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "0"} set negatives to "89ABCDEF" -- Construct a list of the hexadecimal digits, working backwards from the lowest-order one. set widthNow to 0 repeat set c to item (n mod 16 - 1) of o's hexDigits set beginning of o's hexOut to c set n to (n + 1) div 16 - 1 set widthNow to widthNow + 1 -- Finish when n is exhausted, the digit count is a multiple of the resolution, -- and the first digit in the list expresses the negative sign bit. if (n is -1) and (widthNow mod res is 0) and (c is in negatives) then exit repeat end repeat end if -- Coerce the digit list to string. set astid to AppleScript's text item delimiters set AppleScript's text item delimiters to "" set hexOut to o's hexOut as string set AppleScript's text item delimiters to astid return hexOut end numToHex