2025年3月27日 星期四 甲辰(龙)年 月廿六 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Python

Python:to_bytes、to_bytes大端和小端字节和数值转换

时间:05-22来源:作者:点击数:36

语法

  • int.to_bytes(length, byteorder)

参数:

  • length – 所需的数组长度(字节)
  • byteorder – 字节顺序,用于将int转换为字节数组。
    • 字节顺序的值可以是“little”,其中最高有效位存储在末尾,而最低有效位则存储在开头;
    • 也可以是big,其中MSB存储在开头,LSB存储在结尾。

异常:

如果整数值长度不够大,无法容纳在数组的长度中,则返回OverflowError。

  • num = 1
  • print(num.to_bytes(length=8, byteorder='little'))
  • # b'\x01\x00\x00\x00\x00\x00\x00\x00'
  • print(num.to_bytes(length=8, byteorder='big'))
  • # b'\x00\x00\x00\x00\x00\x00\x00\x01'
  • little_byte = b'\x01\x00\x00\x00\x00\x00\x00\x00'
  • print(int.from_bytes(little_byte, byteorder='little'))
  • # 1
  • big_byte = b'\x00\x00\x00\x00\x00\x00\x00\x01'
  • print(int.from_bytes(big_byte, byteorder='big'))
  • # 1
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门