cmaskbitwise-operatorsbit-shiftbitwise-and

Mask and extract bits in C


I've been looking at posts about masks, but I still can't get my head around how to extract certain bits from a number in C.

Say if we have an integer number, 0001 1010 0100 1011, its hexadecimal representation is 0x1A4B, right? If I want to know the 5th to 7th number, which is 101 in this case, shall I use int mask= 0x0000 1110 0000 0000, int extract = mask&number?

Also, how can I check if it is 101? I guess == won't work here...


Solution

  • Assuming the GCC extension 0b to define binary literals:

    int number = 0b0001101001001011; /* 0x1A4B */
    int mask =   0b0000111000000000; /* 0x0E00 */
    /* &'ed:     0b0000101000000000;    0x0A00 */
    int extract = mask & number;     /* 0x0A00 */
    
    if (extract == 0b0000101000000000)
    /* Or if 0b is not available:
    if (extract == 0x0a00 ) */
    {
      /* Success */
    }
    else
    {
      /* Failure */
    }