Javascript:将2D整数数组转换为base64字符串并返回

时间:2017-01-16 15:02:52

标签: javascript arrays

我对javascript不是很熟悉,但是我需要发送和接收大的静态2D整数数组(其中值> 255)作为base64字符串(这是必不可少的)。目前我已经提出了这种简单而低效的解决方案,它们按元素方式转换并手动构造字符串,据我所知,这应该涉及大量数据复制并变得非常慢。

是否可以以更有效的方式完成,如果可能的话,不使用像Node.js这样的大型库等?

     //----------- serializing/deserializing procedures

    //encoding int contours array to be sent as base64 string
    function getBase64IntArray(arr) {

        var width = arr.length;
        //This works given the inner arrays length never changes.
        var height = arr[0].length; 
        //string that would contain data
        var str = width.toString()+","+height.toString()+","; 

        for(var x = 0; x < height; x++) { 
            for(var y = 0; y < width; y++) {
               str = str + arr[x][y].toString() + ","; 
            }
        }      

        var str64 = btoa(str);
        return str64;
    }//getBase64IntArray

    //deconding this string back to array
    function getIntArrayfromBase64(str64) { 

        var str = atob(str64);
        //first occurence of ","
        var width_str = str.substr(0,str.indexOf(',')); 
        str = str.substr(str.indexOf(',')+1); // cut the beginning
        //again first occurence of ","
        var height_str = str.substr(0,str.indexOf(','));
        str = str.substr(str.indexOf(',')+1); // cut the beginning

        var width = parseInt(width_str);
        var height = parseInt(height_str);

        //declare new array and fill it
        var arr = new Array(height);
        var curr_str = "";

        for(var x = 0; x < height; x++) { 

            arr[x] = new Array(width);

            for(var y = 0; y < width; y++) {
               //first occurence of ","
               curr_str = str.substr(0,str.indexOf(',')); 
               // cut the beginning
               str = str.substr(str.indexOf(',')+1); 
               arr[x][y]=parseInt(curr_str);
            }
        }

        return arr;

    }// getIntArrayfromBase64 

发送/接收工作:

    //----------- example usage
    function send(){
    //encoding to base64                
    var arr = [
          [1, 2],
          [3, 4]
    ];

    var base64 = getBase64IntArray(arr);                
    webSocket.send(base64);               
    }

    webSocket.onmessage = function(event){

    //reading array as base64 string
    var arr = getIntArrayfromBase64(event.data);
    var width = arr.length;
    var height = arr[0].length; 

    writeResponse("Received "+width+" "+height+" "+arr[0][0]+arr[1][1]);
    };

1 个答案:

答案 0 :(得分:1)

通过JSON怎么样? JSON将为线格式增加最小的开销,但序列化/反序列化将很快,因为它本地实现。

function getBase64IntArray(arr) { return btoa(JSON.stringify(arr)) }

function getIntArrayfromBase64(str64) { return JSON.parse(atob(str64)) }