Reputation: 5942
I'm trying to translate a Python utility to Ruby. The problem is that don't understand python very well.
A fragment of the utility includes the following if
conditional:
if bits&0x10==0x10:
What does that mean? bits is a variable. Is it some kind of "shortened" "&&", meaning if bits is nonzero and has the value 0x10? Thanks!
Upvotes: 0
Views: 264
Reputation: 63707
It actually checks if the 5th bit of the variable bits is set
How it works
& is bitwise anding.
0x10 is hex of binary value 0b10000
So you do a bit wise anding of what ever is in bits
with 0b10000
Moreover, Ruby supports the similar construct for bit wise testing
if (bits&0x10)
......
end
Note as Tim mentioned, your Python construct can be simplified as
if bits&0x10:
.......
Upvotes: 5
Reputation: 4412
& is the binary bitwise "and" operator.
0x10 is hexadecimal 10.
You may want to read the python docs here
http://docs.python.org/2/reference/expressions.html
Upvotes: 0
Reputation: 3144
The &
alone is the bitwise and operation. Ie, bits
is compared with 0x10 bit by bit and if both have a bit of 1
for that position the result is 1
for that position, otherwise 0.
Basically, since 0x10 is 10000 in binary, this is checking if the 5th bit in bits
is set to 1
.
I don't know much ruby, but my guess is, it should have a bitwise and operator and it would probably be &
as well. Therefore this particular piece of code would end up being exactly the same in ruby.
Edit: according to the Ruby Operators page. Under section "Ruby Bitwise Operators", &
acts as a bitwise and in ruby as well, so you can keep this as is in your translation of utility and it should, indeed, work.
Upvotes: 6