简体   繁体   English

JS十六进制字符串到文件的实际字节值

[英]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 我有一个叫做data的数组,在每个索引处都有一个字节的十六进制字符串,看起来像这样

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? 因此,如果我想编写一个文件,以使从内存地址0x00000000开始的值是该十六进制值的序列,我将如何处理呢?

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. 由于javascript当前没有字节实现,因此您必须将每个字节转换为相应的char,然后写入文件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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