Javascript 使用Big-endian的Int(或short)到字节数组

Javascript 使用Big-endian的Int(或short)到字节数组,javascript,arrays,endianness,Javascript,Arrays,Endianness,我正在尝试创建通用函数来将整数、short和其他函数转换为字节数组,反之亦然,所有这些函数都使用预定义的每值字节计数 编码功能似乎是正确的。看起来是这样的: /**Parameters: data - string, every `bytes` bytes will form one number entry array - the output array refference where numbers will be put bytes - number

我正在尝试创建通用函数来将整数、short和其他函数转换为字节数组,反之亦然,所有这些函数都使用预定义的每值字节计数

编码功能似乎是正确的。看起来是这样的:

  /**Parameters:
     data - string, every `bytes` bytes will form one number entry
     array - the output array refference where numbers will be put
     bytes - number of bytes per entry
     big_endian - use big endian? (little endian otherwise)
  */
  function fromBytes(data, array, bytes, big_endian) {
    //Temporary variable for current number
    var num;
    //Loop through byte array
    for(var i=0, l=data.length; i<l; i+=bytes) {
      num=0;
      //Jump through the `bytes` and add them to number
      if(big_endian) {
        for(var b=0; b<bytes; b++) {
          num+=(num << 8)+data.charCodeAt(i+b);
        }
      }
      else {
        for(var b=bytes-1; b>=0; b--) {
          num+=(num << 8)+data.charCodeAt(i+b);
        }
      }
      //Add decomposed number to an array
      array.push(num);
    }
    return array;
  }

小endian转换是有效的。您能给我一个如何使用Big-endian将int、short或double编码为4、2或8字节的提示吗?

您可以使用小endian进行简单的反向数组,这需要:1。创建一个数组,2。把字节放进去,3。倒过来,4。把它放在绳子上。我需要在这里发挥作用。我相信有一个纯粹的数学解。你能为你的函数提供输入和输出样本吗?
  /**Parameters:
     array - arrau of numbers to encode
     bytes - number of bytes per entry
     big_endian - use big endian? (little endian otherwise)
  */
function toBytes(array, bytes, big_endian) {

    //The produced string
    var data = "";
    //last retrieved number
    var num;
    //Loop through byte array
    for(var i=0, l=array.length; i<l; i++) {
      num = array[i];
      if(big_endian) {
        /** ??? **/
      }
      else {
        for(var b=bytes-1; b>=0; b--) {
          data+=String.fromCharCode(num%255);
          num = Math.floor(num/255);
        }      
      }
      //Add decomposed number to an array
      array.push(num);
    }
    return array;
  }