簡體   English   中英

如何將 int8 數組轉換為二進制並提取 python 中的位

[英]how to convert int8 array to binary and extract bits in python

我有一個帶有 int8 值的巨大 numpy 2D 數組,我想將其轉換為二進制值,提取一個或多個位並構造一個沒有循環的新數組,僅使用np.bitwise_and或此類庫中的方法(例如numpy.where np.bitwise_and )。

例如:

array1 = [4, 128]
array_bits = [[0, 0, 0, 0, 0, 1, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0]]
#or ...
array_bits = ['00000100', '10000000']
#Extracting bit number 3 :
array_res = [1, 0]

我不太確定你為什么不想使用循環(老實說,我想不出沒有循環的方法),但這就是我能找到的。

假設 int8s 的二維數組:

nums = numpy.array([[random.randrange(255) for _ in range(20)],
                    [random.randrange(255) for _ in range(20)]], dtype=numpy.int8)

# Produces
array([[  27, -111,   79, -116, -114,   59,  -12,  -44,  -65,   66,   89,
        -116,    0,   15,  -31,   55,   54, -115,  115,   57],
       [  72,  -57,  -20,  -88,  -94, -112,  -40,   55,   47,  120,  125,
        -101,  117,  -35,  -29,  -41,  -68,  -76,  -11,  -67]], dtype=int8)

您可以使用numpy.ndarray.tostring方法將其轉換為字節數組:

>>> nums.tostring()
b'\x1b\x91O\x8c\x8e;\xf4\xd4\xbfBY\x8c\x00\x0f\xe176\x8ds9H\xc7\xec\xa8\xa2\x90\xd87/x}\x9bu\xdd\xe3\xd7\xbc\xb4\xf5\xbd'

然后您可以使用一些格式(和循環)將其轉換為二進制字符串列表:

>>> bin_strs = [f'{b:08b}' for b in nums.tostring()]
# bin_strs
['00011011',
 '10010001',
 '01001111',
 '10001100',
 '10001110',
 '00111011',
 ...
 ]

然后從那里,您可以使用切片和整數轉換來獲取特定位,盡管您必須向后索引,因為第 0 位在右端:

>>> third_bits = [int(s[-3]) for s in bin_strs]
[0,
 0,
 1,
 1,
 1,
 0,
 ...
 ]

當然結果不是二維的,但你沒有提到它很重要。

我們可以使用np.unpackbits來幫助解決這個問題。 為了讓這個 function 工作,我們需要先將數據轉換為np.uint8

>>> lst = [4, 128]
>>> arr = np.array(lst, dtype=np.uint8)
>>> bits = np.unpackbits(arr)
>>> bits
array([0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], dtype=uint8)

現在要訪問“第 3”位,我們將使用索引 5,因為一個字節中有 8 位,並且您希望第 3 位持續。 然后使用步長 8 繼續在同一 position 處獲取下一個值的位。

>>> bits[5::8]
array([1, 0], dtype=uint8)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM