int main(int argc, char *argv[])
{
  unsigned int number;
  unsigned int size;
  unsigned int mask;
  unsigned int pos;
  printf ("Enter the number : ");
10    scanf ("%x", &number);
11    printf ("Enter position (0-31): ");
12    scanf ("%d", &pos);
13    printf ("Enter mask size (1-%d): ", 32-pos);
14    scanf ("%d", &size);
15    printf ("Number : ");
16    print_bits(number);
17    if(size == 32) {
18      mask = 0xFFFFFFFF;
19    } else {
20      mask = (<< (size + 1)) - 1;
21    }
22    number = (number &  (mask << pos)) >> pos;
23    printf ("\nBits : ");
24    print_bits(number);
25    return 0;
26  }

Output

Enter the number : 55AA55AA55
Enter position (0-31): 3
Enter mask size (1-29): 10
Number : 10101010010101011010101001010101
Bits   : 00000000000000000000010101001010


Number : 10101010010101011010101001010101
Bits   :                ==>10101001010<==

You have viewed 1 page out of 248. Your C learning is 0.00% complete. Login to check your learning progress.

 Vote 0

Similar topics related to this section

basic operators, logical operators, logical vs bitwise operators, logical and bitwise or, bit shifting, obtain bit mask, reverse bits, swap bits, bit set, reset/clear, toggle, xor operator,

# C Programming Language (Prentice Hall Software)
# Let Us C Paperback - 2006 by Yashavant Kanetkar
# Understanding and Using C Pointers Core techniques for memory management
# Data Structures Using C and C++ Paperback - 1998
# Data Structures In C Paperback - August 11, 2008 by Noel Kalicharan