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
3
  • Possible duplicate of What are bitwise shift (bit-shift) operators and how do they work? Commented Jan 10, 2017 at 17:43
  • @EliSadoff no mention of ~ in the question you linked. Commented Jan 10, 2017 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? Commented May 23, 2017 at 18:07

2 Answers 2

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.
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent answer! Note the innermost set of parentheses is redundant: ((2*n)>>1) == (2*n>>1) #=> true.
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!

1 Comment

Concise, to the point and directly addresses the question at hand. Wait...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.