Domanda

I have this array called data and at each index there's a byte's worth of hex strings, it looks like this

var data = new Array("0A", "31", "55", "AA", "FF")

If i inspect the file in a hex editor I should expect to see that sequence. So if I want to write a file so that the values starting at memory address 0x00000000 is that sequence of hex values, how would I go about that?

currently I'm creating the downloadable files with this code.

function download(filename, text) {
   var file = document.createElement('a');
   file.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
   file.setAttribute('download', filename);
   file.click();
}
È stato utile?

Soluzione

You got some hex numbers as strings without the prefix, and you want to write them as bytes to a file. Because there are currently no byte implementations in javascript, you will have to convert each byte to its corresponding char and then write to your file.

var data = new Array("0A", "31", "55", "AA", "FF"), file = "";

//turn hex string to number, then convert it to string and append to file
file += data.map(hex => String.fromCharCode(+("0x"+hex))).join("")

//byte file back to hex array
data = file.split("").map(ch => ("0"+ch.charCodeAt(0).toString(16).toUpperCase()).slice(-2))
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top