使用numpy将一个int转换为一个位数组 [英] using numpy to convert an int to an array of bits

查看:89
本文介绍了使用numpy将一个int转换为一个位数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一种将2000万个32位和64位整数转换为相应的位数组的方法(因此这必须具有内存/时间效率).在另外一个关于此的问题/答案的建议下,我正在尝试使用

I need a way to convert 20 million 32 and 64-bit integers into corresponding bit arrays (so this has to be memory/time efficient). Under advice from a different question/answer here on SO, I'm attempting to do this by using numpy.unpackbits. While experimenting with this method I ran into unexpected results:

np.unpackbits(np.array([1], dtype=np.uint64).view(np.uint8))

产生:

array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=uint8)

我希望1元素是最后一个元素,而不是中间元素.所以我显然缺少保留字节顺序的东西.我想念什么?

I would expect the 1 element to be the last one, but not in the middle. So I'm obviously missing something that preserves the byte order. What am I missing?

推荐答案

尝试:dtype='>i8',就像这样:

In [6]: np.unpackbits(np.array([1], dtype='>i8').view(np.uint8))
Out[6]: 
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], dtype=uint8)

参考:

http://docs.scipy.org/doc/numpy/user/basics.byteswapping.html

这篇关于使用numpy将一个int转换为一个位数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆