“打包”将 4 个 np.uint16 的 np.array 转换为单个 np.unit64
给定 4 个 np.uint16 的 np.array ,
input = np.random.randint(10, size=4, dtype=np.uint16)
如何将它们的二进制表示“打包”到单个 np.uint64 中?
# Example of C code
# output = input[0] | input[1] << 16 | input[2] << 32 | input[3] << 48
4 个 np.uint16 的打包顺序并不重要(只要它不是随机的)。
Given a np.array
of 4 np.uint16
input = np.random.randint(10, size=4, dtype=np.uint16)
how can I "pack" their binary representations into a single np.uint64
?
# Example of C code
# output = input[0] | input[1] << 16 | input[2] << 32 | input[3] << 48
The order in which the 4 np.uint16
are packed is not important (provided it's not random).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 np.view 重新解释数组的字节:
这不会执行任何复制或计算。它执行得很快并且时间恒定。但是,由于字节序,字节顺序依赖于体系结构。它在大多数架构上都是小端字节序,包括 x86-64、大多数 ARM 处理器和最新的 POWER 处理器。
请注意,
input.view(np.uint64).view(np.uint16)
保证为您提供输入数组。请注意,关于所需的字节顺序,您可以交换 Numpy 数组的字节。
You can reinterpret bytes of an array with
np.view
:This does not perform any copy or computation. It is performed quickly and in a constant-time. However, the order of the bytes is architecture-dependent due to the endianness. It is little-endian on most architectures, including x86-64, most ARM processors and recent POWER processors.
Note that
input.view(np.uint64).view(np.uint16)
is guaranteed to give you the input array here.Note that regarding the wanted endianness, you can swap the bytes of Numpy arrays.
这是一个解决方案:
输出:(
旁注:不要使用 Python 内置函数的名称(例如
input
)作为变量名称。:)Here's a solution:
Output:
(Side-note: don't use names of Python builtins (e.g.
input
) as a variable names. :)