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
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
First, let’s understand the operator precedence:
# 5 3 4 1 2
~(~1<<((2*n)>>1))
2*n
multiplies n
by 2
>>1
divides the result by 2
making these two operations completely redundant, the original code is 100% equal to ~(~1<<n)
~1
is a bitwise complement, for 0b01
it is -0b10
, which is -2
,base<<power
is a doubled power, hence we have -2^(5+1) = -64
0b0111111
out of -0b1000000
.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!