0

Question: Provide the binary mask and bit-wise operations to complete the following tasks:

  1. Turn on bits 7,3,1 of an 8-bit binary number (1 is on, 0 is off).
  2. Toggle bits 6,5,4 of an 8 bit binary number

So far I know it is an OR operation because 1 is on, but I don't know how to provide a mask. Do I have to turn 7,3,1 to binary then provide mask?

Duck Dodgers
  • 3,409
  • 8
  • 29
  • 43
Scooby
  • 13
  • 1
  • 7

1 Answers1

0

The details on how to set or toggle bits can be found in this question: How do you set, clear, and toggle a single bit?. You can use a bitshift to set/clear/toggle a single bit, e.g.

x |= (1UL << n); // Set bit n

Or you can use a mask, where you define your desired bits. Here you first need to create a mask, where you set all the bits you want:

unsigned int myBinMask   = 0b00100001;              // Use bit 0 and 5
unsigned int myHexMask   = 0x1C                     // Use bit 2, 3 and 4
unsigned int myShiftMask = (1UL << 1) | (1UL << 7); // Use bit 1 and 7

And then use it like this:

x ^= myBinMask; // Toggel bit 0 and 5
izlin
  • 2,129
  • 24
  • 30