AppleScriptの標準命令でバイナリ書き込み

AppleScriptの標準命令だけでファイルにバイナリ書き込みを行うAppleScriptです。

サードパーティのSatimage OSAXなどを一切使わず、Mac OS Xに標準で用意されている命令だけでファイル書き込みを行います。

コメント欄でdreirossさんから教えていただいたとおり、AppleScriptのRaw Codeを扱う機能を用いて変数へのバイナリデータの保持を行い、通常のwrite命令でファイル書き込みを行います。

AppleScriptのRaw Code指定機能は、アプリケーション側のAppleScript対応度が低いところを無理やりAppleEventを指定して動かしたり、アプリケーション側のAppleScript用語辞書の間違いに左右されずに目的の命令を実行したいケースに使われてきた場合が多く、いわば「奥の手」ともいえる機能。

最近は、そこまでやっかいなScriptingを行うケースもないので、すっかり忘れていましたが……こんな使い方ができたとは。

filebinary.png

本サンプルでは8ビット(0〜255)の間のデータをループでファイルに書き込んでいますが、16ビットや32ビットの値も書き込み(バイナリ変換&書き込み)できるのか試しておきたいところです。

スクリプト名:AppleScriptの標準命令でバイナリ書き込み
set aFile to choose file name with prompt “バイナリ書き込みを行うファイルを指定”

repeat with i from 0 to 255
  –Decimal Number –> Hex String –> AppleEvents Raw Code
  
set oneByteDataHex to aNumToNthDecimal(i, 16, 2, {“0″, “1″, “2″, “3″, “4″, “5″, “6″, “7″, “8″, “9″, “A”, “B”, “C”, “D”, “E”, “F”}, false) of me
  
set oneByteDataBin to run script «data rdat” & oneByteDataHex & » –ここが重要!!
  
  
–File Writing
  
write_to_file(oneByteDataBin, aFile, true) of me
  
end repeat

–10進数をn進数文字列に変換する
–origNum:変換対象の数字
–nTh: n進数のn
–stringLength: 出力指定桁(上位桁のアキはゼロパディングされる)
–zeroSuppress: 上位桁がゼロになった場合に評価を打ち切るかのフラグ、ゼロパディングを行わない(ゼロサプレスする)場合に指定
on aNumToNthDecimal(origNum, nTh, stringLength, stringSetList, zeroSuppress)
  set resString to {}
  
repeat with i from stringLength to 1 by -1
    if {origNum, zeroSuppress} = {0, true} then exit repeat
    
set resNum to (origNum mod nTh)
    
set resText to contents of item (resNum + 1) of stringSetList
    
set resString to resText & resString
    
set origNum to origNum div nTh
  end repeat
  
return (resString as string)
end aNumToNthDecimal

–ファイルの追記ルーチン「write_to_file」
–追記データ、追記対象ファイル、boolean(trueで追記)
on write_to_file(this_data, target_file, append_data)
  try
    set the target_file to the target_file as text
    
set the open_target_file to open for access file target_file with write permission
    
if append_data is false then set eof of the open_target_file to 0
    
write this_data to the open_target_file starting at eof
    
close access the open_target_file
    
return true
  on error error_message
    try
      close access file target_file
    end try
    
return error_message
  end try
end write_to_file

▼新規書類に ▼カーソル位置に ▼ドキュメント末尾に

Leave a Reply