0

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!

2
  • 1
    bitwise "and" Commented Feb 19, 2013 at 17:02
  • BTW, there is no && in python, and bits and 0x10==0x10 will do something quite different. Commented Feb 19, 2013 at 17:06

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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:
    .......

Comments

0

& 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

Comments

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.