You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3.8+pySerial:numpy.int64数组转带符号字节的等效方法

NumPy整数数组转字节的解决方案

问题原因

NumPy的numpy.int64(或numpy.int32)类型元素并非Python原生整数,没有to_bytes()方法,直接调用会报错。以下是两种可行的等效处理方案:

方案1:转换为Python原生整数后调用to_bytes()

适合单个元素的转换场景:

  • 针对numpy.int64类型元素:
    int(int_array[1][i]).to_bytes(8, byteorder='big', signed=True)
    
  • 针对numpy.int32类型元素(或先将原数组转为int32类型):
    int(int_array[1][i].astype('int32')).to_bytes(4, byteorder='big', signed=True)
    

方案2:使用NumPy原生tobytes()方法(更高效,适合批量处理)

NumPy数组及元素自带tobytes()方法,批量处理时效率更高:

  • 单个numpy.int64元素转字节:
    int_array[1][i].tobytes(order='big')
    
  • 单个numpy.int32元素转字节(先转换类型):
    int_array[1][i].astype('int32').tobytes(order='big')
    
  • 整个数组批量转字节(以int32为例):
    int_array.astype('int32').tobytes(order='big')
    

内容的提问来源于stack exchange,提问作者user20035360

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 17:55:15