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

Thread: Bits

  1. #1
    Join Date
    Mar 1999
    Posts
    22

    Bits

    Hi all,

    I have a list like this and would like to know which bits they are:
    0x1 = Bit ?
    0x2 = Bit ?
    0x4
    up to
    0x20000000
    I have a total of 29 values. How can I calcutalte which bit each value is?
    Can anyone help?

    Thanks.
    Martin


  2. #2
    Join Date
    Apr 1999
    Location
    Paris France
    Posts
    134

    Re: Bits

    Hi

    Try something like this


    int WhichBit( long value )
    {
    long mask = 1 ;
    for ( int i = 0 ; i < 32 ; i++ )
    {
    if ( ( mask & value ) != 0 )
    {
    return i+1 ;
    }
    mask <<= 1 ;
    }
    }




    Hope this helps

    Gabriel



  3. #3
    Guest

    Re: Bits

    what is this :
    mark <<= 1 ???


  4. #4
    Join Date
    Apr 1999
    Location
    Paris France
    Posts
    134

    Re: Bits

    it is the same as

    mask = mask << 1



    operator << shifts bits to the left


  5. #5
    Join Date
    Sep 1999
    Location
    NJ
    Posts
    1,299

    Re: Bits

    That presumes that value only has one bit set. (If it has more than one bit set, it will only find the least significant). If you are going to use that assumption, we can simplify it a bit more:

    int WhichBit(long value)
    {
    int bit = 0;
    while (value != 0)
    {
    value >>= 1;
    bit++;
    }
    return (bit);
    }



    This returns zero if no bit is set, or the position (1-32) of the most significant bit set.


    Truth,
    James
    http://www.NJTheater.com
    http://www.NJTheater.com/JamesCurran

  6. #6
    Join Date
    Aug 1999
    Posts
    11

    Re: Bits

    Hi,
    I hope it is in powers of 2.

    int GetBitPos(long value)
    {
    long mask = 1;
    int ct = 0;
    while(ct < 32)
    {
    if ( value & mask )
    {
    return ct;
    }
    value >>= 1;
    ct++;
    }
    return -1;
    }




    Hope this helps
    Viswanathan


  7. #7
    Guest

    Re: Bits

    Tnx Gabriel


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