将字节数组写入二进制文件Javascript

时间:2014-10-07 19:53:22

标签: javascript binaryfiles binary-data

我正在尝试编写一个生成随机数的脚本,然后将这些数字转换为4Bytes组,然后将这些4字节组放入Uint8Array中,最后我尝试将数组保存到二进制文件中。这是我的代码:

<html>
<head>
<title>Raandom Number Generator</title>
</head>
<body>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="filesaver.min.js"></script>
<script type="text/javascript">
    $(function() {
        if (!Date.now) {
            Date.now = function() {
                return new Date().getTime();
            };
        }

        alert("started");
        var currentMousePos = {
            x : -1,
            y : -1
        };
        var randomData = [];
        var bytes = new Int8Array(4);

        $(document).mousemove(function(event) {

            if(randomData.length>=1231){
                $(document).unbind('mousemove');
                console.log("Finished generating numbers ... trying to save file");
                randomData = new Uint8Array(randomData);
                var blob = new Blob(randomData, {type: "application/octet-stream"});
                saveAs(blob, "rand.bin");
                return;
            }
            currentMousePos.x = event.pageX;
            currentMousePos.y = event.pageY;
            var longRandomNumber = Date.now() * (event.pageX + 1)
                    * (event.pageY + 1);
            for ( var i = 3; i >= 0; i--) {
                bytes[i] = longRandomNumber & (255);
                longRandomNumber = longRandomNumber >> 8
            }
            for ( var i = 0; i < 4; i++) {
                randomData.push(bytes[i]);
            }
            console.log(randomData.length);
        });
    })
</script>
</body>
</html>

问题是生成的文件包含数字plain numbers,例如Uint8Array中的元素可能是65,在我对二进制的理解中,这个值应该保存为大写字母 A 但是它存储为 65 而不是

注意

filesaver.min.js是一个用于从JS保存文件的库(Link on GitHub

1 个答案:

答案 0 :(得分:3)

Blob constructor确实希望连接类型数组的数组,但是只传递一个Uint8Array。这可能会被解释为(我应该说,“转换为”?)一组DOM字符串 - 这就是你的数字的来源。

quickfix将使用

new Blob([randomData], {type: "application/octet-stream"})
//       ^          ^

但我建议要么

var randomData = [];
// while randomData.length < 308
    var bytes = new Uint8Array(4);
    for (var i=4; i--; ) {
        bytes[i] = longRandomNumber & (255);
        longRandomNumber = longRandomNumber >> 8
    }
    randomData.push(bytes);

var blob = new Blob(randomData, {type: "application/octet-stream"});

或者根本不使用那些4字节bytes数组:

var randomData = new Uint8Array(1232),
    count = 0;
// while count < randomData.length
    for (var i=4; i--; ) {
        randomData[count++] = longRandomNumber & (255);
        longRandomNumber = longRandomNumber >> 8
    }

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