1

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]

The idea is that a one would be a true and zero would be a false. It would be adequate to get it as an array of zeros and ones but true and false would be much more preferable.

Thanks in advance for any help.

user3380049
  • 139
  • 1
  • 10

3 Answers3

3

Try this:

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

p x
slapthelownote
  • 4,249
  • 1
  • 23
  • 27
2

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.

Stefan
  • 109,145
  • 14
  • 143
  • 218
1

See this answer of mine to a similar question: Looping through bits in an integer.

Here's the gist of it:

In Ruby, Integers (i.e. both Bignums and Fixnums) can already be indexed as if they were bit arrays. They are, however, not Enumerable.

But you can fix that, of course:

class Integer
  include Enumerable

  def each
    return to_enum unless block_given?      
    (size*8).times {|i| yield self[i] }
  end
end

A slightly less intrusive way might be to represent the Integer as an array:

class Integer
  def to_a
    Array.new(size*8, &method(:[]))
  end
end

Then you can use Ruby's nifty Enumerable methods:

5.to_a.map {|b| !b.zero? }
# => [true, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false]
Community
  • 1
  • 1
Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653