二进制矢量与128位数字之间的转换



是否有一种方法可以在二进制向量和128位数字之间来回转换?我有以下二进制向量:

import numpy as np
bits = np.array([1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1,
0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0,
1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1,
0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1,
1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1], dtype=np.uint8)

这是一个MD5哈希,我试图将其用作scikit-learn机器学习分类器的特征(我需要将哈希表示为单个特征)。

如上所述,numpy最多只能输入64位,但python有可变长度的int,所以我们可以使用128位int,没有问题。

下面将从np中的二进制开始。np.array.

import numpy as np
bits = np.array(
[
1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1,
0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0,
1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1,
0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1,
1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1
],
dtype=np.uint8
)
s = "".join(bits.astype("str"))  # move from array to string
n = int(s, 2)  # convert to int from string of base 2
print(n)
s = bin(n)[2:]  # get binary of int, cut "0b" prefix
np.array(list(s), dtype=np.uint8)  # put back in np.array

最新更新