Thread: Determine powers of base 2 from their sum

1. Determine powers of base 2 from their sum

Okay, I'm not sure that's the best title, but let me explain.

I'm coding something that takes a sum of the powers of base as an argument, but the number of elements in the sum is variable, and not necessarily continuous in the powers.
The particular variable is called mode, and mode could be any of the following (the maximum power used is 6, the minimum power is 0):
(2^0)
or
(2^1) + (2^3)
or
(2^1) + (2^2) + (2^5)
or
(2^0) + ..... + (2^6)

My question:
All I know is the sum of these (i.e. So, I only know 1 or 9 or 38 or 127 - respectively).
How can I work out what the individual powers of 2 were which were passed, from this sum?

(Might I be better off converting the number to binary and comparing for matches bit by bit?)

Thanks

2. Re: Determine powers of base 2 from their sum

Originally Posted by SimpleOne
(Might I be better off converting the number to binary and comparing for matches bit by bit?)
Yes. If none of the coefficients of powers is greater than 1 (i.e., if you don't have sums like 3 * (2^1) + 2^3), then the easiest thing in a language like C is to use bit operators to reveal individual bits. For example, to find the coefficient of 2^3 (0 or 1) you can use (mode >> 3) & 1 (this needs to be checked).

3. Re: Determine powers of base 2 from their sum

Hi,

Thanks for the response, i did indeed end up going for bitwise comparison, my brain absolutely failed to come up with anything else.

Cheers