1

Bitwise operators is tough to understand. Can somebody explain the ruby code below in detail?

 def res(n)
 ~(~1<<((2*n)>>1))
 end

 res(5) --> 63
Rikkas
  • 572
  • 4
  • 19
  • Possible duplicate of [What are bitwise shift (bit-shift) operators and how do they work?](http://stackoverflow.com/questions/141525/what-are-bitwise-shift-bit-shift-operators-and-how-do-they-work) – Eli Sadoff Jan 10 '17 at 17:43
  • @EliSadoff no mention of `~` in the question you linked. – Sagar Pandya Jan 10 '17 at 18:21
  • There is a lot chained together there. Is there any useful purpose for it or does it just happen to be somebody's sample/example? – Douglas G. Allen May 23 '17 at 18:07

2 Answers2

8

First, let’s understand the operator precedence:

# 5 3  4   1   2
  ~(~1<<((2*n)>>1))
  1. 2*n multiplies n by 2
  2. >>1 divides the result by 2 making these two operations completely redundant, the original code is 100% equal to ~(~1<<n)
  3. ~1 is a bitwise complement, for 0b01 it is -0b10, which is -2,
  4. base<<power is a doubled power, hence we have -2^(5+1) = -64
  5. bitwise complement again produces 0b0111111 out of -0b1000000.
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
1

Update edit.

Let's describe as well as we may what is going on and what order they are in here. First let me give credit to the first answer about the redundancy of the original expression. I start with the simple one.

def bitwise_complement_bits(args)
  ~ args
end

def bitwise_shift_left(o, n)
  o << n
end

a = bitwise_complement_bits(1)
b = bitwise_shift_left(a, 5)
p bitwise_complement_bits(b)

Update edit:

Here's a nifty site for some quick evaluation of code.

I just pasted in what we had here. You may step though it there and really see what is going on.

Or you can use your own installation as well as repl.it https://repl.it/languages/ruby Have fun!

Douglas G. Allen
  • 2,203
  • 21
  • 20
  • Concise, to the point and directly addresses the question at hand. Wait... –  Jan 11 '17 at 11:44