“打包”将 4 个 np.uint16 的 np.array 转换为单个 np.unit64

发布于 2025-01-15 01:12:51 字数 332 浏览 7 评论 0原文

给定 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

花想c 2025-01-22 01:12:51

您可以使用 np.view 重新解释数组的字节:

input.view(np.uint64) # 844429225558024 on my x86-64 machine

这不会执行任何复制或计算。它执行得很快并且时间恒定。但是,由于字节序,字节顺序依赖于体系结构。它在大多数架构上都是小端字节序,包括 x86-64、大多数 ARM 处理器和最新的 POWER 处理器。

请注意,input.view(np.uint64).view(np.uint16) 保证为您提供输入数组。

请注意,关于所需的字节顺序,您可以交换 Numpy 数组的字节

You can reinterpret bytes of an array with np.view:

input.view(np.uint64) # 844429225558024 on my x86-64 machine

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.

巴黎夜雨 2025-01-22 01:12:51

这是一个解决方案:

output = np.bitwise_or.reduce(input << (np.arange(len(input)) * 16))

输出:(

>>> output
281483566710792

旁注:不要使用 Python 内置函数的名称(例如 input)作为变量名称。:)

Here's a solution:

output = np.bitwise_or.reduce(input << (np.arange(len(input)) * 16))

Output:

>>> output
281483566710792

(Side-note: don't use names of Python builtins (e.g. input) as a variable names. :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文