hex <–––> ascii

Here’s a little script that converts between ascii and hex -

on hex(txt)
	set hx to {}
	set txt to txt as text
	set hexc to "123456789abcdef"
	repeat with achar in txt
		set char to ASCII number achar
		set r to char mod 16
		set d to char div 16
		if d as integer = 0 then
			set hx to hx & "0" as text
		else
			set hx to hx & (item d of hexc) as text
		end if
		if r as integer = 0 then
			set hx to hx & "0" as text
		else
			set hx to hx & (item r of hexc) as text
		end if
	end repeat
	return hx
end hex

on unhex(hex)
	
	set sep to {}
	set hex to hex as text
	set hexc to "123456789abcdef"
	set cc to count of hex
	set ticker to 0
	repeat while ticker < (cc - 1)
		set ticker to ticker + 1
		if ticker mod 2 ≠ 0 then
			set sep to sep & ((items ticker through (ticker + 1) of hex) as text) as list
		end if
	end repeat
	
	set txt to {}
	
	repeat with acode in sep
		set n to item 1 of (acode as text)
		set r to item 2 of (acode as text)
		try
			if n as integer = 0 then
				set n to 0
			else
				set n to offset of n in hexc
			end if
		on error
			set n to offset of n in hexc
		end try
		
		try
			if r as integer = 0 then
				set r to 0
			else
				set r to offset of r in hexc
			end if
		on error
			set r to offset of r in hexc
		end try
		
		set currchar to (n * 16 + r) as integer
		set txt to txt & (ASCII character currchar) as text
	end repeat
	return txt
end unhex

hex("¡zapatos!")
--"c17a617061746f7321"
unhex("c17a617061746f7321")
  --  "¡zapatos!"

Hi, Alex.

That seems to work very well. :slight_smile: May I offer a slight simplification?

on hex(txt)
	set hx to ""
	set txt to txt as text
	set hexc to "0123456789abcdef"
	
	repeat with achar in txt
		set char to ASCII number achar
		set r to char mod 16
		set d to char div 16
		set hx to hx & character (d + 1) of hexc & character (r + 1) of hexc
	end repeat
	
	return hx
end hex

on unhex(hex)
	
	set txt to ""
	set hex to hex as text
	set hexc to "0123456789abcdef"
	set cc to (count hex)
	if (cc mod 2 is 1) then set hex to "0" & hex
	
	repeat with i from 1 to cc by 2
		set n to ((offset of (character i of hex) in hexc) - 1) * 16 + (offset of (character (i + 1) of hex) in hexc) - 1
		set txt to txt & (ASCII character n)
	end repeat
	
	return txt
end unhex

hex("¡zapatos!")
unhex(result)

Coolness!
Thanks, Nigel Garvey :cool:

Interesting little glitch, Nigel – I had to change the variable name “txt” to something else or the script errored (access not allowed) on txt as text in the third line. :confused:

Hmmm. Sound like a name-space conflict with something. A third-party OSAX, perhaps? :confused: