【问题标题】:How does Python convert and calculate an int to byte Little Endian (.to_bytes(4, 'little')) - python to javascript(nodejs)Python 如何将 int 转换为字节 Little Endian (.to_bytes(4, 'little')) - python to javascript(nodejs)
【发布时间】:2022-01-03 12:25:47
【问题描述】:

如何将 int 转换为 Uint8Array 作为 javascript(nodejs) 中的小端序

在 python 中将 int 转换为字节时,我得到了这个输出

int(20).to_bytes(2, 'little') # out as Uint8Array([20,0]) <- 2 bytes
int(60).to_bytes(2, 'little') # out as Uint8Array([60,0]) <- 2 bytes
int(256).to_bytes(2, 'little') # out as Uint8Array([0,1]) <- 2 bytes(0,1 <-- 255 +1)
int(512).to_bytes(2, 'little') # out as Uint8Array([0,1]) <- 2 bytes(0,2 <-- 256*2)
int(1641167820).to_bytes(4, 'little') # out as Uint8Array([204,59,210,97])<- 4 bytes(0,2)

..一个字节中的最大数量是(255), 它在nodejs中有一些内置函数与python中的(.to_bytes)相同吗?

【问题讨论】:

    标签: javascript python node.js byte uint8array


    【解决方案1】:

    基本上我必须创建一个函数来做同样的事情 如图所示 -> https://newbedev.com/converting-javascript-integer-to-byte-array-and-back

    longToByteArray =(long) => {
      // we want to represent the input as a 8-bytes array
      var byteArray = [0, 0, 0, 0, 0, 0, 0, 0];
    
      for ( var index = 0; index < byteArray.length; index ++ ) {
          var byte = long & 0xff;
          byteArray [ index ] = byte;
          long = (long - byte) / 256 ;
      }
    
      return byteArray;
    };
    

    【讨论】:

      猜你喜欢
      • 2022-06-10
      • 1970-01-01
      • 1970-01-01
      • 2018-12-09
      • 2017-08-26
      • 2021-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多