473,569 Members | 2,536 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Determining combination of bits

Say I have a dictionary like the following

{1:'one',2:'two ',4:'three',8:' four',16:'five' , etc...}

and I am given some numbers, say 22, 25, and 9. I want to determine the
keys, powers of 2, that comprise the number.

Ex. 22 = 16+4+2
25 = 16+8+1
9 = 8+1
....etc...

How do I get these keys?
Jul 18 '05 #1
25 1839
Sean Berry <sean <at> buildingonline. com> writes:

I want to determine the keys, powers of 2, that comprise the number.

Ex. 22 = 16+4+2
25 = 16+8+1
9 = 8+1
...etc...


This sounds suspiciously like a homework, so I'm just going to give a hint here:
import math
math.log(22, 2) 4.4594316186372 973 2**int(math.log (22, 2)) 16 2**int(math.log (22 - 16, 2)) 4 2**int(math.log (22 - 16 - 4 - 2, 2)) 2


Hope this is helpful.

Steve

Jul 18 '05 #2
You didn't say anything about how large the
numbers might get. If they stay small (e.g. <thousands)
you could just look them up directly from a dictionary.
If they can get arbitrarily large you must use bit
shifing and boolean & (and).

Sounds a lot like a homework assignment, but I'll
give you some "hints".

1) Use bit shifting operator (>>) and boolean &
operator to isolate each bit in the integer.

2) It will be either zero or one. Build up a
list of these which will represent the power
of two that each one bit represents.

Larry Bates

Sean Berry wrote:
Say I have a dictionary like the following

{1:'one',2:'two ',4:'three',8:' four',16:'five' , etc...}

and I am given some numbers, say 22, 25, and 9. I want to determine the
keys, powers of 2, that comprise the number.

Ex. 22 = 16+4+2
25 = 16+8+1
9 = 8+1
...etc...

How do I get these keys?

Jul 18 '05 #3

"Sean Berry" <se**@buildingo nline.com> wrote in message
news:x3Qjd.1217 86$hj.41260@fed 1read07...
and I am given some numbers, say 22, 25, and 9. I want to determine the
keys, powers of 2, that comprise the number.
How do I get these keys?


if n%2: print 'has a positive one bit'

n//2 == n>>1 deletes that bit

keep track of divisions/shifts and stop when n == 0

Terry J. Reedy

Jul 18 '05 #4
Just to set everyone's mind at ease... I haven't had a homework assignment
for about four years now.

I am using two database tables. One will have some options and a code
(power of 2).

Then, someone will check off checkboxes and submit. The number will be
added and saved in a cookie. Then, later, I want to be able to redisplay
their choices by reading the value from the cookie.

I expect the values will get no bigger than 2^32 = 4294967296. Is this
getting too big???

"Terry Reedy" <tj*****@udel.e du> wrote in message
news:ma******** *************** *************** @python.org...

"Sean Berry" <se**@buildingo nline.com> wrote in message
news:x3Qjd.1217 86$hj.41260@fed 1read07...
and I am given some numbers, say 22, 25, and 9. I want to determine the
keys, powers of 2, that comprise the number.
How do I get these keys?


if n%2: print 'has a positive one bit'

n//2 == n>>1 deletes that bit

keep track of divisions/shifts and stop when n == 0

Terry J. Reedy

Jul 18 '05 #5
Sean Berry <sean <at> buildingonline. com> writes:

I am using two database tables. One will have some options and a code
(power of 2).

Then, someone will check off checkboxes and submit. The number will be
added and saved in a cookie. Then, later, I want to be able to redisplay
their choices by reading the value from the cookie.


You might look at the number_in_base thread:

http://groups.google.com/groups?thre...%40news.oz.net

This gives a solution something like:
def number_in_base( n, b=10, digits='0123456 789ABCDEF'): .... return '-'[:n<0]+''.join(revers ed(list(
.... digits[r]
.... for q in [abs(n)]
.... for q, r in iter(lambda: divmod(q, b), (0, 0))))) or digits[0]
.... digits = number_in_base( 22, 2)
[power_of_2

.... for power_of_2, digit
.... in zip(reversed([2**x for x in range(len(digit s))]), digits)
.... if digit == '1']
[16, 4, 2]
Steve

Jul 18 '05 #6
Sean Berry wrote:
Just to set everyone's mind at ease... I haven't had a homework assignment
for about four years now.

OK, then here's a great little bit of education:

n & -n == least significant bit of n

So, for example:

def bits(n):
assert n >= 0 # This is an infinite loop if n < 0
while n:
lsb = n & -b
yield lsb
n ^= lsb

-Scott David Daniels
Sc***********@A cm.Org
Jul 18 '05 #7
Scott David Daniels wrote:
Sean Berry wrote:
Just to set everyone's mind at ease... I haven't had a
homework assignment for about four years now.

OK, then here's a great little bit of education:

n & -n == least significant bit of n


A lapse of mind?
n = 6
n & (-n)

2

You probably meant n&1 or perhaps n%2.
Jul 18 '05 #8
> A lapse of mind?
n = 6
n & (-n)

2

You probably meant n&1 or perhaps n%2.


No, the exact right thing: 6 is binary

110

with the least significant bit beeing

10

thus the decimal value of 2.

Albeit I have to admit that I didn't know the trick.
--
Regards,

Diez B. Roggisch
Jul 18 '05 #9
On 2004-11-08, Diez B. Roggisch <de*********@we b.de> wrote:
A lapse of mind?
> n = 6
> n & (-n)

2

You probably meant n&1 or perhaps n%2.


No, the exact right thing: 6 is binary

110

with the least significant bit beeing

10


The least significant bit of 110 is this one here -----+
^ |
| |
+-----------------------+

It's a 0 (zero).

What I think you're trying to say is something like the value
of the rightmost 1.

--
Grant Edwards grante Yow! The PINK SOCKS were
at ORIGINALLY from 1952!! But
visi.com they went to MARS around
1953!!
Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

19
8801
by: cppaddict | last post by:
Hi, I am going to have a series of bit flags which I could store in an array, or as a string ("10011001"), or any other way. I want to be able to turn this series of bits into an int. I know C++ must have some class or built-in functionality for this, but my web searching thus far hasn't found it. Can someone let me know what I should...
4
1427
by: - Dazed | last post by:
If a user is using a combination of Win98 & any version of MSIE, I want to display a message. The best that I can do is the following: <? if ((strstr (getenv('HTTP_USER_AGENT'), 'MSIE')) && (strstr (getenv('HTTP_USER_AGENT'), '98'))) { echo"blah,blah,blah\n"; } ?>
7
4793
by: sathyashrayan | last post by:
Group, Following function will check weather a bit is set in the given variouble x. int bit_count(long x) { int n = 0; /* ** The loop will execute once for each bit of x set,
4
2146
by: Lachlan Hunt | last post by:
Hi, I'm looking for an interoperable method of determining the current background colour of an element that is set using an external stylesheet. I've tried: elmt.style.backgroundColor; but that only works if the colour has been set using the style attribute or previously set using script. I've also tried:
6
4512
by: aka_eu | last post by:
I have this problem. I'm trying to get all the valid combination C(N,K) that pass one condition. For example C(5,3) can use in any combination this numbers {1,2,3,4,5} But let's say that I have the limitations that these pair of numbers cannot be part of the same combination {2,3} and {4,5}
15
4784
by: steve yee | last post by:
i want to detect if the compile is 32 bits or 64 bits in the source code itself. so different code are compiled respectively. how to do this?
6
2821
by: John Messenger | last post by:
I notice that the C standard allows padding bits in both unsigned and signed integer types. Does anyone know of any real-world examples of compilers that use padding bits? -- John
16
2878
by: Dom Fulton | last post by:
Has anyone got a mechanism for finding the number of bits in floats, doubles, and long doubles? I need this to communicate with some hardware. I guess I could try to deduce this from float.h, but that looks difficult. I don't mind something which is system-specific; the older gccs had various defines in cpu_limits.h and related files,...
9
469
by: Ioannis Vranos | last post by:
Under C++03: Is it guaranteed that char, unsigned char, signed char have no padding bits?
0
7924
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7676
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7974
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6284
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5219
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3653
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3642
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2114
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1221
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.