-2
class example(Enum):
   x1 = 0
   x2 = 1
   x3 = 2
   x4 = 4
   x5 = 8
   x6 = 16
   ...

If I have the number 12, how do I know that it matches x4 + x5?

The x-numbers are always power of 2

Francesco
  • 175
  • 2
  • 3
  • 8
  • This looks like you want to convert a decimal number to binary. If that is what you want to do, you can easily find a the process for converting from one base to another and implement that. This might help (if your x-values are intentionally powers of 2): https://stackoverflow.com/questions/699866/python-int-to-binary – L. MacKenzie Oct 14 '17 at 13:45
  • are your x-numbers random or are they powers of 2 like you have it now? When they are powers of 2 then just use the binary representation of the given number (12 = 0b1100) to see which powers of 2 contribute to it. – trincot Oct 14 '17 at 13:46
  • If you do not answer whether the x's are the powers of two, your question is unclear and will probably be closed before it is answered fully. So please answer the question asked of you. – Rory Daulton Oct 14 '17 at 14:20
  • Yes. the x's are always power of 2 – Francesco Oct 14 '17 at 14:48

1 Answers1

0

It seems as if you are trying to convert denary to binary. It is a good exercise to try and do this yourself, but storing the powers of 2 in different variables is not a good idea as it will not scale when trying to convert larger numbers...

So, yes, you could write your own algorithm for doing this, but if you aren't fussed, just use Python's built-in bin function.

From the docs:

Convert an integer number to a binary string. The result is a valid Python expression. If x is not a Python int object, it has to define an index() method that returns an integer.

So as an example, if you wanted to know the binary value of 12, you could do:

bin(12)

which would give:

'0b1100'

Hope this helps!

Joe Iddon
  • 20,101
  • 7
  • 33
  • 54