2017-01-16 55 views
1

我對javascript並不熟悉,但我需要發送和接收大的靜態2D整數數組(其值> 255)作爲base64字符串(這是必要)。目前,我已經想出了這個簡單而低效的解決方案,將它們轉換爲元素方式並手動構建字符串,據我所知,這應該涉及大量的數據複製,並且變得非常緩慢。Javascript:將2D整數數組轉換爲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

有關通過JSON會如何? JSON將爲線路格式增加最小的開銷,但序列化/反序列化將會很快,因爲它是本地實現的。

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

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

+0

謝謝!有用!! – Slowpoke

+0

還有一個額外的問題:有什麼方法可以在C++中解碼這些數據嗎?什麼是轉換算法? – Slowpoke

+0

https://github.com/nlohmann/json –

相關問題