Make array of bools out of Ruby integer bits

来源:互联网 发布:ip扫描软件 编辑:程序博客网 时间:2024/05/20 01:35

Okay, so I was wondering if I could create an array of Boolean values from an integer by using its bits. For example, if I wanted to use 5, which is 101 in binary, is there any reasonably easy way that I could get this in something of the form:

[true, false, true]

This would work:

num = 5(0...num.bit_length).map { |i| num[i] == 1 }#=> [true, false, true]

or

(0...num.bit_length).map { |i| num[i] == 1 }.reverse#=> [true, false, true]

depending on the desired bit order.

Try this:

x = 5.to_s(2).split(//).collect do |n|  n == "1"endp x

0 0
原创粉丝点击