簡體   English   中英

在python中將8位列表轉換為32位整數數組

[英]Convert a 8bit list to a 32 bit integer array in python

我有的 :

textdata = "this is my test data"
DataArray = [ord(c) for c in textdata]

現在我想通過將列表的4個元素組合在一起將其轉換為x 32位整數

例如:DataArray [0:4]將成為32位整數,然后迭代到接下來的4個元素並執行相同的操作。 最后,我將得到一個包含所有結果的32位數組。

我如何在python遍歷整個字符串的過程中做到這一點。 有沒有簡單的方法可以做到這一點?

只要您的字符串是4的整數倍,就可以以非常有效的方式使用NumPy:

import numpy as np
data = np.fromstring(textdata, dtype='>u4')
# array([1952999795,  543781664, 1836654708, 1702065184, 1684108385])

'>u4'表示“大端無符號4字節整數”。

編輯 :如果您使用NumPy> = 1.14,則不np.fromstring使用np.fromstring ,處理文本的正確方法是調用np.frombuffer(textdata.encode(), dtype='>u4')

使用numpy:

>>> import numpy as np

>>> a = np.frombuffer(b'this is my test data', dtype=np.int32)
>>> a
array([1936287860,  544434464, 1948285293,  544502629, 1635017060], dtype=int32)
>>> a.tobytes()
b'this is my test data'

使用'<i4'或類似的dtype表示在機器之間可移植的字節序。

我假設您可以將初始數據保留為bytes而不是unicode ,因為您確實應該努力做到這一點。

您可以使用struct內置的python模塊:

from struct import unpack

textdata = "this is my test data"
data = list(unpack('i'*(len(textdata)//4), textdata))

結果:

[1936287860, 544434464, 1948285293, 544502629, 1635017060]

例如,如果要使用無符號整數,則不需要遍歷字符串,並且可以找到其他格式字符

您可以使用類似以下的東西,它使用位操作(大端):

def chunk2int(chunk):
    """ Converts a chunk (string) into an int, 8 bits per character """
    val = 0
    for c in chunk:
        val = (val << 8) | (ord(c) & 0xFF)
    return val

def int2chunk(val):
    """ Converts an int into a chunk, consuming 8 bits per character """
    rchunk = []
    while val:
        rchunk.append(val & 0xFF)
        val >>= 8

    return ''.join(chr(c) for c in reversed(rchunk))

textdata = "this is my test data"

chunks = [textdata[i:i + 4] for i in range(0, len(textdata), 4)]
print(chunks)

data = [chunk2int(c) for c in chunks]
print(data)

chunks = [int2chunk(d) for d in data]
print(chunks)

生產:

['this', ' is ', 'my t', 'est ', 'data']
[1952999795, 543781664, 1836654708, 1702065184, 1684108385]
['this', ' is ', 'my t', 'est ', 'data']

如果您在輸入文本中使用1 <= ord(c) <= 255的字符,則可以使用。 如果您的字符串中int2chunk字節,則int2chunk方法可能會提前終止,在這種情況下,您必須填充這些塊。

還有struct模塊,可能值得研究,在這里您可以更簡單地更改字節序。

暫無
暫無

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

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