CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6

Threaded View

  1. #1
    Join Date
    Feb 2009
    Location
    New York
    Posts
    8

    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
  •  





Click Here to Expand Forum to Full Width

Featured