如何在Crystal中有效地操作二进制数?

How to manipulate binary numbers efficiently in Crystal?

我正在尝试实现比特币规范 BIP-39,特别是 Generating the mnemonic 部分。以下内容引起一些头痛:

Next, these concatenated bits are split into groups of 11 bits, each encoding a number from 0-2047, serving as an index into a wordlist. Finally, we convert these numbers into words and use the joined words as a mnemonic sentence.

将二进制数分成 11 位一组。但是我如何在 Crystal 中有效地做到这一点?

这是我所做的,我个人觉得它有点尴尬,但不可否认它有效:

seed = "87C1B129FBADD7B6E9ABC0A9EF7695436D767AECE042BEC198A97E949FCBE14C0d"
# => "87C1B129FBADD7B6E9ABC0A9EF7695436D767AECE042BEC198A97E949FCBE14C0d"

bin = BigInt.new(seed, 16).to_s(2)
# => "100001111100000110110001001010011111101110101101110101111011011011101001101010111100000010101001111011110111011010010101010000110110110101110110011110101110110011100000010000101011111011000001100110001010100101111110100101001001111111001011111000010100110000001101"

iter = 0
size = 11
while iter < bin.size
  p bin[iter, size]
  # => "10000111110"
  # [...]
end

现在,正如我所说,它起作用了,我可以获取二进制字符串并将它们转换回数字并继续,但这不可能。我想知道,什么是更优雅、更高效或更 正确 的方法来解决这个问题?

很抱歉给出简洁的答案,但我认为您要找的是 BitArray。希望对你有用!