Search code examples
cbit-manipulation

Finding Bit Positions in an unsigned 32-bit integer


I think I might have been asleep in my CS class when they talked about Bit Positions, so I am hoping someone can lend a hand.

I have a unsigned 32-bit integer (Lets use the value: 28)

According to some documentation I am going over, the value of the integer contains flags specifying various things.

Bit positions within the flag are numbered from 1 (low-order) to 32 (high-order). All undefined flag bits are reserved and must be set to 0.

I have a Table that shows the meanings of the flags, with meaning for the numbers 1-10.

I am hoping that someone can try and explain to me what this all means and how to find the "flag" value(s) from a number like, 28, based off of bit position.

Thanks


Solution

  • 28 converts to 11100 in binary. That means bits 1 and 2 are not set and bits 3, 4 and 5 are set.

    A few points: first, anybody who's really accustomed to C will usually start the numbering at 0, not 1. Second, you can test of individual flags with the bitwise and operator (&), as in:

    #define flag1 1    //  1 = 00 0001
    #define flag2 2    //  2 = 00 0010
    #define flag3 4    //  4 = 00 0100
    #define flag4 8    //  8 = 00 1000
    #define flag5 16   // 16 = 01 0000
    #define flag6 32   // 32 = 10 0000
    
    if (myvalue & flag1)
        // flag1 was set
    
    if (myvalue & flag4)
        // flag4 was set
    

    and so on. You can also check which bits are set in a loop:

    #include <stdio.h>
    
    int main() { 
        int myvalue = 28;
        int i, iter;
    
        for (i=1, iter=1; i<256; i<<=1, iter++)
            if (myvalue & i)
                printf("Flag: %d set\n", iter);
        return 0;
    }
    

    should print:

    Flag: 3 set
    Flag: 4 set
    Flag: 5 set