I need to get the nth bit of an integer, signed or unsigned, in Ruby.
x = 123
n = 2
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?
source
share