我正在寻找一个比Pythons在构建的"to_bytes“中使用的更快的函数。我需要传递给"to_bytes“的参数。
(示例:数据的列表、byte_size和字节顺序)。
任何帮助都将不胜感激!
发布于 2022-09-21 13:09:24
不是完整的答案,而是指向可能的解决方案的指针。np.view( dtype = np.uint8
可用于逐字节获取数组的字节视图。
import numpy as np
np.random.seed( 1234 )
arr = np.random.randint( 10000, size = 10, dtype = np.int16 ) - 2000
arr
# array([ 6915, -682, 6002, 5221, 2445, 5540, 5347, -1336, 317, 4137], dtype=int16)
b_arr = arr.view( np.uint8 ).reshape( -1,2 )
b_arr
# Col0 Col1 = Res0
# array([[ 3, 27], # 3 + 27*256 = 6915
# [ 86, 253], # 86 + 253*256 = 64854 - 65536 = -682 Subtract 65536 if Res0 > 32767
# [114, 23],
# [101, 20],
# [141, 9],
# [164, 21],
# [227, 20],
# [200, 250],
# [ 61, 1],
# [ 41, 16]], dtype=uint8)
可以根据需要对上面的内容进行操作,以获得小/大的端点。np.dtype
允许数据处于1、2、4或8字节的布局中。然后忽略不需要的列。
结果b_arr
的endianness将取决于运行代码的处理器的endianness。
编辑更进一步的想法。
系统的字节顺序在sys库中。一个可能的函数np_to_bytes
import sys
byte_lu = [ np.int8, np.int8, np.int16, np.int32, np.int32, np.int64, np.int64, np.int64, np.int64]
cols_lu = [ 1, 1, 2, 4, 4, 8, 8, 8, 8, 8 ]
def np_to_bytes( int_list, n_bytes, endian = sys.byteorder ):
arr = np.array( int_list, dtype = byte_lu[ n_bytes ])
b_arr = arr.view( np.uint8 ).reshape(-1, cols_lu[ n_bytes ])
if sys.byteorder != endian:
b_arr = b_arr[ :, ::-1] # Reverse the columns to change the endian.
if sys.byteorder != endian:
b_arr = b_arr[ :, ::-1] # Reverse the columns to change the endian.
if endian == 'little':
return b_arr[ :, : n_bytes ]
return b_arr[ :, -n_bytes: ]
https://stackoverflow.com/questions/73799871
复制相似问题