简体   繁体   中英

JS hex string to actual byte values of a file

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();
}

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM