Convert «data rdatNN» to hex digit?

This should be easy, but I can’t figure out the answer and would be grateful for any help.

I’m working on a script that reads the first few bytes of a binary file and performs different actions depending on the data it finds.

In testing, I would like to be able to do something like this:

display dialog testByte

where testByte is something like «data rdat2C»

How can I convert «data rdat2C» to the string “2C” or to its decimal equivalent?

Thanks for any help.

You can read it “as text” and then get the id of the characters.

Yes, that works. Thank you!

ASCII number might be better (while it works), id of text will make some conversions:


set s to (ASCII character 128)
id of s

Yes, you’re correct. Reading as «class utf8» would be safer with id, but then it might not be valid UTF8.

For a hexadecimal string, there’s the old “deliberate error” hack:

set theData to (read (choose file) for 3 as data)
try
	|| of theData
on error errMsg
	set astid to AppleScript's text item delimiters
	set AppleScript's text item delimiters to {"«data rdat", "»"} -- Snow Leopard or later.
	set hexStr to errMsg's middle text item
	set AppleScript's text item delimiters to astid
end try

display dialog hexStr

For a list of byte values, you can either derive it from the above string or do something like this:

on byteValues(f, n)
	-- Well need to read an even number of bytes from the file. Make sure the file's long enough.
	set readLen to (n + n mod 2) -- n rounded up to a multiple of 2.
	if (readLen > (get eof f)) then
		-- Deal with this.
	end if
	
	set sInts to (read f from 1 for readLen as short) -- A list of (originally 2-byte) integers.
	set bVals to {} -- For the byte-values output.
	repeat with i from 1 to n
		if (i mod 2 is 1) then -- Getting the value of an odd-numbered byte.
			-- Get the next short integer from sInts and make sure it's interpreted as a positive value.
			set thisInt to ((item (i div 2 + 1) of sInts) + 65536) mod 65536
			-- Append its hi-byte value to the byte-value list. 
			set end of bVals to thisInt div 256
		else -- Even numbered byte.
			set end of bVals to thisInt mod 256
		end if
	end repeat
	
	return bVals
end byteValues

byteValues(choose file, 3)