C - Mask to select multiple bits from a variable.

Introduction

The following code sets a value in a variable and then uses the bitwise operators to reverse the sequence of hexadecimal digits.

Demo

#include <stdio.h>

int main(void)
{
  unsigned int original = 0xDEAD;
  unsigned int result = 0;
  unsigned int mask = 0xF;          // Rightmost four bits

  printf("\n original = %X", original);

  // Insert first digit in result
  result |= original & mask;        // Put right 4 bits from original in result

                    // Get second digit
  original >>= 4;                   // Shift original right four positions
  result <<= 4;                     // Make room for next digit
  result |= original & mask;        // Put right 4 bits from original in result

    /* Get third digit */
  original >>= 4;                   // Shift original right four positions
  result <<= 4;                     // Make room for next digit
  result |= original & mask;        // Put right 4 bits from original in result

  printf("\t result = %X\n", result);
  return 0;/*from   w  w w  .  j  a va2s  . c  o  m*/
}

Result

Related Topic