Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract bit in Ruby Integers

I need to get the n-th bit of an Integer, either signed or unsigned, in Ruby.

x = 123 # that is 1111011
n = 2   # bit 2 is ...0 

The following piece of code doesn't work in the general case:

x.to_s(2)[-(n+1)] #0 good! but...

because of negative numbers not represented as 2-complement:

-123.to_s(2) # "-1111011"

So how to proceed?

like image 216
JCLL Avatar asked Aug 18 '11 15:08

JCLL


3 Answers

x = 123 # that is 1111011
n = 2   # bit 2 is ...0

x[n]    # => 0

-123[2] # => 1
like image 174
Jörg W Mittag Avatar answered Oct 29 '22 15:10

Jörg W Mittag


def f x, bit
  (x & 1 << bit) > 0 ? 1 : 0
end
like image 22
DigitalRoss Avatar answered Oct 29 '22 16:10

DigitalRoss


You could try the Bindata lib.

There is a function to represent an integer's binary representation as a string, and after that, you can do what you like with it.

like image 45
Dmitri Avatar answered Oct 29 '22 15:10

Dmitri