|
-
April 11th, 2009, 10:33 PM
#1
Some bitwise problems..
I have a short (16bits) storing true and false (1 and 0) in the lower 9 bits, and I want to be able to count the number of 1s (or 0).
Example: 0000000010111010 (answer would be 5 in this case, total # of 1s)
This is what I came up with(assuming n is the value and total is the amount of 1s):
Code:
int i = 0, total = 0;
while(i++ < 9)
total += 1 - ~((n >>> 1) | 0xFFFE);
Is there a better way to do it in O(1) instead of O(n)?
Thanks in advance.
Last edited by VolatileObject; April 11th, 2009 at 10:36 PM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|