2017-02-14 53 views
0

我想寫入數組(1,2)到二進制文件作爲字節。 所以輸出文件應該包含00000001 00000010. 我明白我必須使用ADODB.Stream,但我還沒有找到任何解決方案這樣簡單的任務。上述如何使用JScript將字節序列寫入二進制文件?

var data = new Array(1, 2)  
out = WScript.CreateObject("ADODB.Stream") 
out.Type = 1 
out.Open() 
out.Write(data) 
out.SaveToFile("output.bin", 2) 
out.Close() 

代碼給出錯誤:

參數的錯誤類型,超出可接受的範圍內,或在彼此的衝突。

任何想法如何將數據數組轉換爲可接受的類型?

+0

這裏的關鍵是使用type = text並進行代碼頁轉換,就像在我的答案中鏈接的文章中所解釋的那樣。在同一篇文章中,您還會發現反向函數_ReadAll_,將其用作概念證明,以讀回保存的文件。 – deblocker

回答

1

您可以使用WriteAll功能描述在這裏:Reading and Writing Binary Files Using JScript。版權:Alexander J Turner博士。

請注意,應是文本類型,然後您將需要執行文本< - >二進制轉換。 我只是測試了所有的代碼,它對我來說工作得很好。

下面是一個完整的例子:

var bf1 = new BinaryFile("C:/Temp/test.bin"); 
var outBuf = ''; 
for(var i=0, l=data.length; i<l; i++) { 
    outBuf += String.fromCharCode(data[i]); 
} 
bf1.WriteAll(outBuf); 

結果看起來是這樣的:

enter image description here

編輯:

我只是做的代碼更緊湊適應,以避免十六進制轉換和雙循環:

// Codepage conversion table 
var _c=[199,252,233,226,228,224,229,231,234,235,232,239,238,236,196,197, 
     201,230,198,244,246,242,251,249,255,214,220,162,163,165,8359,402, 
     225,237,243,250,241,209,170,186,191,8976,172,189,188,161,171,187, 
     9617,9618,9619,9474,9508,9569,9570,9558,9557,9571,9553,9559,9565,9564,9563,9488, 
     9492,9524,9516,9500,9472,9532,9566,9567,9562,9556,9577,9574,9568,9552,9580,9575, 
     9576,9572,9573,9561,9560,9554,9555,9579,9578,9496,9484,9608,9604,9612,9616,9600, 
     945,223,915,960,931,963,181,964,934,920,937,948,8734,966,949,8745, 
     8801,177,8805,8804,8992,8993,247,8776,176,8729,183,8730,8319,178,9632,160], 
    _w=[], 
    _r=[]; 

// Create forward lookup to write & reverse lookup to read 
for(var i=0, l=256; i<l; i++) { 
    var c = (i<128) ? i : _c[i-128]; 
    _w[i] = c; 
    _r[c] = i; 
} 

// Read binary data from disk  
function binFileToArray(fileName, binArray){ 
    var inStream = new ActiveXObject("ADODB.Stream"); 
    inStream.Type = 2; 
    inStream.CharSet = '437'; 
    inStream.Open(); 
    inStream.LoadFromFile(fileName); 
    var inString = inStream.ReadText(); 
    inStream.Close(); 
    for(var i=0, l=inString.length; i<l; i++) { 
     binArray.push(_r[inString.charCodeAt(i)]); 
    } 
} 

// Write binary data to disk 
function binArrayToFile(binArray, fileName){ 
    var outStream = new ActiveXObject('ADODB.Stream'); 
    var outString = ''; 
    for(var i=0, l=binArray.length; i<l; i++) { 
     outString += String.fromCharCode(_w[binArray[i]]); 
    } 
    outStream.Type = 2; 
    outStream.CharSet = '437'; 
    outStream.Open(); 
    outStream.WriteText(outString); 
    outStream.SaveToFile(fileName, 2); 
    outStream.Close(); 
} 

// TEST: read binary file from disk & write array back to disk 

var testArray = []; 
binFileToArray('c:/temp/test.bin', testArray); 
binArrayToFile(testArray, 'c:/temp/test2.bin'); 

// both files equals 
相關問題