日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python整数转字节数组_【转】Python内置函数(7)——bytearray

發布時間:2024/9/27 python 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python整数转字节数组_【转】Python内置函数(7)——bytearray 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

英文文檔:

class bytearray([source[, encoding[, errors]]])

Return a new array of bytes. The bytearray class is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the bytes type has, see Bytes and Bytearray Operations.

The optional source parameter can be used to initialize the array in a few different ways:If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode().

If it is an integer, the array will have that size and will be initialized with null bytes.

If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array.

If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.

Without an argument, an array of size 0 is created.

說明:

1. 返回值為一個新的字節數組

2. 當3個參數都不傳的時候,返回長度為0的字節數組

>>> b = bytearray()

>>> b

bytearray(b'')

>>> len(b)

0

3. 當source參數為字符串時,encoding參數也必須提供,函數將字符串使用str.encode方法轉換成字節數組

>>> bytearray('中文')

Traceback (most recent call last):

File "", line 1, in

bytearray('中文')

TypeError: string argument without an encoding

>>> bytearray('中文','utf-8')

bytearray(b'\xe4\xb8\xad\xe6\x96\x87')

4. 當source參數為整數時,返回這個整數所指定長度的空字節數組

>>> bytearray(2)

bytearray(b'\x00\x00')

>>> bytearray(-2) #整數需大于0,使用來做數組長度的

Traceback (most recent call last):

File "", line 1, in

bytearray(-2)

ValueError: negative count

5. 當source參數為實現了buffer接口的object對象時,那么將使用只讀方式將字節讀取到字節數組后返回

6. 當source參數是一個可迭代對象,那么這個迭代對象的元素都必須符合0 <= x < 256,以便可以初始化到數組里

>>> bytearray([1,2,3])

bytearray(b'\x01\x02\x03')

>>> bytearray([256,2,3]) #不在0-255范圍內報錯

Traceback (most recent call last):

File "", line 1, in

bytearray([256,2,3])

ValueError: byte must be in range(0, 256)

總結

以上是生活随笔為你收集整理的python整数转字节数组_【转】Python内置函数(7)——bytearray的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。