Javascript: how to convert hex data to binary and write it into a file

浪尽此生 提交于 2020-01-02 06:44:12

问题


I have a bunch of hex values and I have to convert it into binary data before write them into a file.

I trasformed the hex string in an array of integers, then I convert each integer to a char:

// bytes contains the integers
str = String.fromCharCode.apply(String, bytes);

now I create the blob file and download it:

var blob = new Blob([str], {type: "application/octet-stream"});
saveAs(blob, "file.bin");

but something goes wrong: if I print the length of bytes and the length of str I have the same value (512), but the file contains 684 chars, and of course it isn't how I expect it.

So I have:

512 pairs of hex values -> 512 integers -> 512 chars -> I save the file -> 684 chars inside the file.

What am I doing wrong? I even tried to add the charset to the blob file, ie:

var blob = new Blob([str], {type: "application/octet-stream;charset=UTF-8,"});

but with no success.

EDIT:

Original HEX:

Saved file:


回答1:


Thanks to Andrey I found the solution:

I have to write in binary mode, so:

var ab = new ArrayBuffer(bytes.length); //bytes is the array with the integer
var ia = new Uint8Array(ab);

for (var i = 0; i < bytes.length; i++) {
  ia[i] = bytes[i];
}

var blob = new Blob([ia], {type: "application/octet-stream"});
saveAs(blob, id + "_<?php echo $report['md5']; ?>.bin");


来源:https://stackoverflow.com/questions/31827901/javascript-how-to-convert-hex-data-to-binary-and-write-it-into-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!