2016年6月8日水曜日

バイナリデータを読み書きするサンプル

バイナリ形式でファイルを読んだり書いたりできます。
このサンプルファイルに適当なファイルをドラッグ&ドロップすると、そのファイルと同じフォルダに「(ファイル名)_書き換え後」というファイルを作成します。
書き換えたい場合は一番下の実行結果の画像を参考にして、書き換えたい部分の特定&リプレイスして、改行コードを削除してからbin_write関数に渡してください。
<job>
<script>
arg = WScript.Arguments
if(!arg.length){ WScript.Quit() }
bin_write = function(path,v){
var str = WScript.CreateObject('ADODB.Stream');
str.type = 2 //adTypeText
str.charset = 'iso-8859-1'
str.open()
v = v.split('')
for(var i=0,L=v.length,int_; i<L; i+=3){
try{
eval('int_ = 0x' + v[i] + v[i+1])
}catch(e){
return WScript.Echo('i:'+i+'\nv[i]:'+v[i]+'\nv[i+1]:'+v[i+1]+'\n')
}
str.writeText(String.fromCharCode(int_))
}
str.saveToFile(path, 2)
str.close()
str = null
}
bin_read = function(path){
var me=arguments.callee
if(!me.func){
// 変換がおかしいところは~0xffの範囲外
var REPLSRC = [
0x20ac, 0x81 , 0x201a, 0x192 , 0x201e, 0x2026, 0x2020, 0x2021,
0x2c6 , 0x2030, 0x160 , 0x2039, 0x152 , 0x8d , 0x17d , 0x8f ,
0x90 , 0x2018, 0x2019, 0x201c, 0x201d, 0x2022, 0x2013, 0x2014,
0x2dc , 0x2122, 0x161 , 0x203a, 0x153 , 0x9d , 0x17e , 0x178
]
var REPLDST = [
0x80 , 0x81 , 0x82 , 0x83 , 0x84 , 0x85 , 0x86 , 0x87 ,
0x88 , 0x89 , 0x8a , 0x8b , 0x8c , 0x8d , 0x8e , 0x8f ,
0x90 , 0x91 , 0x92 , 0x93 , 0x94 , 0x95 , 0x96 , 0x97 ,
0x98 , 0x99 , 0x9a , 0x9b , 0x9c , 0x9d , 0x9e , 0x9f
]
var obj={}
for(var i=0,L=REPLSRC.length;i<L;i++){ obj[REPLSRC[i]] = REPLDST[i] }
me.func=function(path){
var txt='', out='', c=0, idx=0
with(WScript.CreateObject('ADODB.Stream')){
type = 2 //adTypeText
charset = 'iso-8859-1'
open()
loadFromFile(path)
txt = readText()
close()
}
for(var i=0,L=txt.length; i<L;i++){
c = txt.charCodeAt(i)
c = obj[c] || c
out += (c < 0x10) ? '0' + c.toString(16) : c.toString(16)
out += ' ';
if (i % 16 == 15 && i >= 0xf) out += '\n'
}
return out
}
}
return me.func(path)
}
fs = new ActiveXObject('Scripting.FileSystemObject')
path = arg(0)
path出力 = fs.GetParentFolderName(path)+'/'+fs.GetBaseName(path)
bin = bin_read(path)
bin_write( path出力+'_書き換え後.'+fs.GetExtensionName(path) , bin.replace(/\n/g,'') )
with(fs.CreateTextFile(path出力+'_バイナリ文字列.txt')){Write(bin.replace(/\n/g,'\r\n'));Close()}
</script>
</job>

実行結果

0 件のコメント:

コメントを投稿