1

I'd like to write a method that takes an integer and a bit length and returns an array of integers corresponding to the bits.

For example:

decompose(100, 4)
#=> [4, 12]

because:

100 is 01001100 in binary
        /   \
      0100  1100
       4      12

decompose(123456, 6)
#=> [1, 8, 60, 0]

because:

123456 is 000001001000111100000000 in binary
           /       |     |      \
          1        8     60      0

Note: I don't need to worry about bit lengths that aren't exact divisors.

1
  • I don't think you have the right number. Commented Sep 29, 2012 at 16:44

2 Answers 2

2
def decompose n, l, a = []
  n, r = n.divmod(2 ** l)
  a.unshift(r)
  n.zero? ? a : decompose(n, l, a)
end

decompose(100, 4) # => [6, 4]
decompose(123456, 6) # => [30, 9, 0]
Sign up to request clarification or add additional context in comments.

Comments

0

How about this?

def decompose(num, len)
  num.to_s(2).chars.each_slice(len).map { |x| x.join.to_i(2) }.reverse
end

decompose(100, 4)
#=> [4, 12]

Or this:

def decompose(num, len)
  num.to_s(2).scan(/.{1,len}/).map { |x| x.to_i(2) }.reverse
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.