Extract bits in Ruby Integer

I need to get the nth bit of an integer, signed or unsigned, in Ruby.

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

The following code does not work in the general case:

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

due to negative numbers not represented as 2-complement:

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

So how to proceed?

+5
source share
3 answers
x = 123 # that is 1111011
n = 2   # bit 2 is ...0

x[n]    # => 0

-123[2] # => 1
+12
source
def f x, bit
  (x & 1 << bit) > 0 ? 1 : 0
end
+4
source

You can try Bindata lib .

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

+3
source

All Articles