Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - get bit range from variable

I have a variable and want to take a range of bits from that variable. I want the CLEANEST way to do this.

If x = 19767 and I want bit3 - bit8 (starting from the right): 100110100110111 is 19767 in binary. I want the part in parenthesis 100110(100110)111 so the answer is 38.

What is the simplest/cleanest/most-elegant way to implement the following function with Ruby?

bit_range(orig_num, first_bit, last_bit)

PS. Bonus points for answers that are computationally less intensive.

like image 467
Selah Avatar asked Nov 08 '12 22:11

Selah


2 Answers

19767.to_s(2)[-9..-4].to_i(2)

or

19767 >> 3 & 0x3f

Update:

Soup-to-nuts (why do people say that, anyway?) ...

class Fixnum
  def bit_range low, high
    len = high - low + 1
    self >> low & ~(-1 >> len << len)
  end
end

p 19767.bit_range(3, 8)
like image 64
DigitalRoss Avatar answered Sep 25 '22 14:09

DigitalRoss


orig_num.to_s(2)[(-last_bit-1)..(-first_bit-1)].to_i(2)
like image 33
SwiftMango Avatar answered Sep 23 '22 14:09

SwiftMango