Fixing up my hex to decimal converter. Anybody know a good easy way to make this case insensitive. I thought of changing the characters to match the characters in the passed set of base numbers, but that would add too much. Making two sets of base numbers is also a bit to much. I’m thinking that the subroutine might have to be more specific in what it handles.
property hex_chars : "0123456789ABCDEF"
set h to "AF"
BaseToDec(h, hex_chars)
--
-- converts a base string to decimal integer
-- case sensetive because of the offset command
on BaseToDec(h, base_chars)
set m to length of base_chars
set n to 0
set i to -1
repeat with this_char in reverse of characters of h
set i to i + 1
set o to (offset of this_char in base_chars)
if o is 0 then
set n to 0
exit repeat
end if
set char_val to o - 1
set n to n + char_val * (m ^ i)
end repeat
return n
end BaseToDec
That works! I didn’t know that. Here’s what I’ll use then:
set t to "0123456789abcdef" as Unicode text
set utid to AppleScript's text item delimiters
set AppleScript's text item delimiters to "F"
set temp_l to text items of t
set AppleScript's text item delimiters to utid
set char_val to (count item 1 of temp_l)
Some time ago (can’t find it) Nigel posted this version which will deal with signed hex:
on hexToNum from h given sign:sign
script o
property hexChrs : "0123456789abcdef" as Unicode text -- TIDs are case insensitive with Unicode.
on getHexVal(c)
set AppleScript's text item delimiters to c
set v to (count text item 1 of hexChrs)
if (v is 16) then error "Non-hex character(s)."
return v
end getHexVal
end script
set astid to AppleScript's text item delimiters
try
set h to h as Unicode text -- Speeds up use of TIDs with Unicode 'hexChrs' in o.
tell o to set n to getHexVal(character 1 of h)
if (sign) and (n > 7) then set n to n - 16
repeat with i from 2 to (count h)
tell o to set n to n * 16 + getHexVal(character i of h)
end repeat
on error msg number errNum
set AppleScript's text item delimiters to astid
error "hexToNum handler: " & msg number errNum
end try
set AppleScript's text item delimiters to astid
return n
end hexToNum
hexToNum from "00000000043e9207" without sign
--> 71209479
hexToNum from "FFFE" without sign
--> 65534
hexToNum from "FFFE" with sign
--> -2
On both my machines, TIDs are case sensitive when the main text is a string, but obey the current setting of the case attribute (‘considering case’ or ‘ignoring case’) when the main text is Unicode.
On my Jaguar machine, ‘offset of’ is case sensitive with both strings and Unicode text. On my Tiger machine, it obeys the case attribute with both strings and Unicode text.
The class of the delimiter or of the searched-for substring can be either string or Unicode text without affecting the result.